DEV Community

Cover image for You have been zigged (series) : Writing to spawned child process's stdin
Black Tornado
Black Tornado

Posted on

You have been zigged (series) : Writing to spawned child process's stdin

In this blog, we will explore how to spawn a child process and write content into its stdin.

// sortusingpipe__main.zig
const std = @import("std");

pub fn main(init: std.process.Init) !void {
    var buffer: [1024]u8 = undefined;
    const argv = [_][]const u8{"sort"};
    var child = try std.process.spawn(init.io, .{ .argv = &argv, .stderr = .inherit, .stdin = .pipe, .stdout = .inherit });
    defer child.kill(init.io);
    const child_stdin = child.stdin orelse return error.MissingStdinPipe;
    var writer = std.Io.File.Writer.init(child_stdin, init.io, &buffer);
    try writer.interface.print("Ziyad\nAnand\nArjun\nRam\nHooper\n", .{});
    try writer.flush();
    child_stdin.close(init.io); // send EOF to sort command. without this sort will wait infinitly
    child.stdin = null; // set child.stdin = null (avoids a Zig 0.16 debug double-close panic)
    _ = try child.wait(init.io);
}
Enter fullscreen mode Exit fullscreen mode

Running the program with zig run sortusingpipe__main.zig will print the names in ascending order.

Anand
Arjun
Hooper
Ram
Ziyad
Enter fullscreen mode Exit fullscreen mode

Thanks for reading. To be continued.

Top comments (0)