Skip to content

Commit 7cb6146

Browse files
author
Jan Philipp Hafer
committed
fix potential leaks and improve comments
1 parent 127651b commit 7cb6146

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

test/standalone/childprocess_extrapipe/child.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@ pub fn main() !void {
1111
_ = it.next() orelse unreachable; // skip binary name
1212
const s_handle = it.next() orelse unreachable;
1313
var file_handle = try std.os.stringToHandle(s_handle);
14+
defer std.os.close(file_handle);
1415

1516
// child inherited the handle, so inheritance must be enabled
1617
const is_inheritable = try std.os.isInheritable(file_handle);
1718
std.debug.assert(is_inheritable);
1819

1920
try std.os.disableInheritance(file_handle);
2021
var file_in = std.fs.File{ .handle = file_handle }; // read side of pipe
21-
defer file_in.close();
2222
const file_in_reader = file_in.reader();
2323
const message = try file_in_reader.readUntilDelimiterAlloc(gpa, '\x17', 20_000);
2424
defer gpa.free(message);

test/standalone/childprocess_extrapipe/parent.zig

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,21 @@ pub fn main() !void {
2020
const child_path = it.next() orelse unreachable;
2121

2222
var pipe = try child_process.portablePipe();
23-
24-
// write read side of pipe to string + add to spawn command
25-
var buf: [os.handleCharSize]u8 = comptime [_]u8{0} ** os.handleCharSize;
26-
const s_handle = try os.handleToString(pipe[pipe_rd], &buf);
27-
var child_proc = ChildProcess.init(
28-
&.{ child_path, s_handle },
29-
gpa,
30-
);
31-
32-
// enabling of file inheritance directly before and closing directly after spawn
33-
// less time to leak => better
23+
defer os.close(pipe[pipe_wr]);
24+
var child_proc: ChildProcess = undefined;
25+
// spawn block ensures read end of pipe always closed + shortly closed after spawn().
3426
{
35-
try os.enableInheritance(pipe[pipe_rd]);
3627
defer os.close(pipe[pipe_rd]);
3728

29+
var buf: [os.handleCharSize]u8 = comptime [_]u8{0} ** os.handleCharSize;
30+
const s_handle = os.handleToString(pipe[pipe_rd], &buf) catch unreachable;
31+
child_proc = ChildProcess.init(
32+
&.{ child_path, s_handle },
33+
gpa,
34+
);
35+
36+
// less time to leak read end of pipe => better
37+
try os.enableInheritance(pipe[pipe_rd]);
3838
try child_proc.spawn();
3939
}
4040

@@ -43,7 +43,6 @@ pub fn main() !void {
4343
std.debug.assert(!is_inheritable);
4444

4545
var file_out = std.fs.File{ .handle = pipe[pipe_wr] };
46-
defer file_out.close();
4746
const file_out_writer = file_out.writer();
4847
try file_out_writer.writeAll("test123\x17"); // ETB = \x17
4948
const ret_val = try child_proc.wait();

0 commit comments

Comments
 (0)