VOOZH about

URL: https://dev.to/black_tornado/you-have-been-zigged-series-run-a-child-process-4df9

⇱ You have been zigged (series) : Run a child process - DEV Community


In this blog we will see how to run a child process from a zig program. There are two std lib functions that allows us to do this - std.process.run() and std.process.spawn(). Lets see how we can use both.

Method 1: std.process.run()

The run function allows us to run a process without much hassle. The following program runs ls -l and prints out the output in stdout. ls is a linux command. If you are on windows, you can use dir instead.

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

pub fn main(init: std.process.Init) !void {
 const argv = [_][]const u8{ "ls", "-l" };
 const result = try std.process.run(init.gpa, init.io, .{ .argv = &argv });
 defer init.gpa.free(result.stderr);
 defer init.gpa.free(result.stdout);

 var buffer: [1024]u8 = undefined;
 var file_writer = std.Io.File.Writer.init(.stdout(), init.io, &buffer);
 var stdout_writer = &file_writer.interface;
 try stdout_writer.print("{s}", .{result.stdout});
 try stdout_writer.flush();
}

We can compile the program using zig build-exe runprocess__main.zig. Upon execution, this program will print the contents of current directory.

Method 2: std.process.spawn()

The spawn function gives us fine-grained control over the process.

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

pub fn main(init: std.process.Init) !void {
 const argv = [_][]const u8{
 "ls",
 "-l",
 };

 var child = try std.process.spawn(init.io, .{
 .argv = &argv,
 .stdin = .inherit,
 .stdout = .inherit,
 .stderr = .inherit,
 });

 _ = try child.wait(init.io);
}

We can compile the program using zig build-exe runprocessspawn__main.zig. Upon execution, this program will print the contents of current directory.

Thanks for reading. To be continued.