VOOZH about

URL: https://dev.to/black_tornado/you-have-been-zigged-series-writing-to-spawned-child-processs-stdin-ng6

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


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);
}

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

Anand
Arjun
Hooper
Ram
Ziyad

Thanks for reading. To be continued.