Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Last active May 16, 2022 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matu3ba/69c9d99a573594bfde416eb1527b5b4e to your computer and use it in GitHub Desktop.
Save matu3ba/69c9d99a573594bfde416eb1527b5b4e to your computer and use it in GitHub Desktop.
Pipe in Zig. Notice that EOF can only be read once child or parent close the pipe. Doesnt matter if we dup or not.
const std = @import("std");
const os = std.os;
pub fn main() !void {
const alloc = std.testing.allocator;
const pipe = try os.pipe(); // read end [0], write end [1]
const read_dup = try os.dup(pipe[0]);
const write_dup = try os.dup(pipe[1]); // for simplicity
const pid_result = try os.fork();
if (pid_result == 0) {
std.debug.print("child spawned\n", .{});
// we are the child
const rd_pipe = std.fs.File{ .handle = read_dup };
os.close(pipe[0]);
os.close(pipe[1]);
os.close(write_dup);
const content = try rd_pipe.reader().readAllAlloc(alloc, 10_000);
std.debug.print("content: {s}\n", .{content});
// usually we exec here, but in this example we do something simpler
rd_pipe.close();
} else {
std.debug.print("parent spawned\n", .{});
// we are the parent
const wr_pipe = std.fs.File{ .handle = pipe[1] };
os.close(pipe[0]); // close read end
os.close(read_dup);
os.close(write_dup);
try wr_pipe.writer().writeAll("test123123123123123123blablabla\n"); // no \n to test things
std.debug.print("waiting for child to print stuff\n", .{});
while (true) {
std.time.sleep(1_000_000_000);
std.debug.print("tick\n", .{});
}
wr_pipe.close(); // close write end
// we must close or think of a delimiter
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment