Skip to content

Zig Processes

Sometimes the easiest way to get something done is to run a program that already does it: git to find the current commit, zig version to check the compiler, a converter, a test runner. Your program starts it as a child process, waits for it, and looks at what it printed and how it ended. This page shows the two ways to do that in Zig 0.17: std.process.run when you just want the output, and std.process.spawn when you want more control. It also covers the things that trip people up: there’s no shell, exit codes can mean different things, and the program you want might not exist.

std.process.run starts a program, waits until it finishes, and hands you everything it printed. This one asks the Zig compiler for its version:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const result = try std.process.run(gpa, init.io, .{
.argv = &.{ "zig", "version" },
});
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
const version = std.mem.trimEnd(u8, result.stdout, "\r\n");
std.debug.print("You have Zig {s}\n", .{version});
std.debug.print("It {f}\n", .{result.term});
}

You’ll see:

You have Zig 0.17.1
It exited with code 0

Here’s what’s happening:

  • .argv is the command as a list: the program name first, then each argument as its own string. It’s the same list the child will see as its args, so "zig" is its args[0] and "version" its args[1] (see Zig Command-Line Arguments).
  • Zig looks the program name up in your PATH, the same way your shell does, so "zig" works if typing zig in a terminal works.
  • result.stdout and result.stderr are everything the child wrote to each stream, as allocated strings. You own them, so free both.
  • Output almost always ends with a newline, which you usually don’t want. std.mem.trimEnd(u8, text, "\r\n") removes it (the \r matters on Windows).
  • result.term says how the child ended. More on that next.

run gives the child an empty stdin, so programs that wait for typed input see the end of input right away instead of hanging.

Every process ends with an exit code: 0 for success, anything else for some kind of failure. result.term is a std.process.Child.Term, a tagged union with four cases:

Case Meaning
.exited It ended normally, with this exit code (u8).
.signal It was killed by a signal, like Ctrl+C or kill -9 (Linux and macOS).
.stopped It was paused by a signal.
.unknown It ended in a way Zig couldn’t classify.

For a quick yes or no, term.success() is true only for .exited with code 0. To react to the details, switch on it:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const result = try std.process.run(gpa, init.io, .{
.argv = &.{ "ls", "/does-not-exist" },
});
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
std.debug.print("ls said: {s}", .{result.stderr});
switch (result.term) {
.exited => |code| if (code == 0) {
std.debug.print("success\n", .{});
} else {
std.debug.print("failed with exit code {d}\n", .{code});
},
else => std.debug.print("ended abnormally: {f}\n", .{result.term}),
}
}

You’ll see:

ls said: ls: cannot access '/does-not-exist': No such file or directory
failed with exit code 2

The important bit: a child that fails is not an error in your program. run succeeded (it ran ls and collected its output), so try doesn’t complain. Whether ls itself worked is in term, and checking it is your job. Forgetting to check is a very common bug: the program carries on with empty output as if everything were fine.

What the codes mean is up to each program. ls uses 2 for “serious trouble”, grep uses 1 for “no match” (which often isn’t a problem at all), and many programs simply use 1 for every failure. Check the program’s documentation before you treat a specific code as fatal.

If the program can’t be found, run itself fails, before anything runs:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const result = std.process.run(gpa, init.io, .{
.argv = &.{"no-such-program"},
}) catch |err| switch (err) {
error.FileNotFound => {
std.debug.print("no-such-program isn't installed (or isn't in PATH)\n", .{});
return;
},
else => return err,
};
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
}

You’ll see:

no-such-program isn't installed (or isn't in PATH)

So there are two different ways to fail: the program couldn’t start (an error from run, like FileNotFound or AccessDenied), and the program ran and reported failure (a non-zero code in term). Good tools tell the user which one happened, because the fixes are different: “install it” versus “look at its error message”.

When you type ls *.zig in a terminal, the shell expands *.zig into a list of matching files before ls ever runs. std.process.run doesn’t use a shell. It starts the program directly with exactly the strings you give it:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const result = try std.process.run(gpa, init.io, .{ .argv = &.{ "ls", "*.zig" } });
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
std.debug.print("{s}", .{result.stderr});
}

You’ll see:

ls: cannot access '*.zig': No such file or directory

ls got the literal text *.zig and looked for a file with that exact name. The same goes for everything else the shell normally does for you: no $VARIABLES, no ~, no | pipes, no > redirection, no &&.

That sounds like a limitation, but it’s mostly a gift:

  • No quoting headaches. A file name with spaces is just one string in argv: &.{ "rm", "my file.txt" }. No escaping needed.
  • No injection. If part of the command comes from a user, say a file name, it can’t sneak in extra commands like ; rm -rf ~, because nothing parses it. It’s just one argument.

If you really need shell features, run a shell and give it a command string: &.{ "sh", "-c", "ls *.zig | wc -l" } on Linux and macOS. Then the injection risk is back, so never paste user input into that string. Pass it as a separate argument or avoid the shell.

run collects all the output in memory and only gives it to you at the end. For a long-running program, or one that should print straight to the user (a build, a test run, an editor), use std.process.spawn and wait. By default the child inherits your stdin, stdout and stderr, so its output appears in the terminal as it happens.

This small runner program starts whatever command you give it, waits, and passes the child’s exit code on as its own:

const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(init.arena.allocator());
if (args.len < 2) {
std.debug.print("usage: runner <program> [args...]\n", .{});
return 2;
}
var child = std.process.spawn(init.io, .{ .argv = args[1..] }) catch |err| {
std.debug.print("runner: could not start '{s}': {t}\n", .{ args[1], err });
return 127;
};
const term = try child.wait(init.io);
std.debug.print("runner: '{s}' {f}\n", .{ args[1], term });
return switch (term) {
.exited => |code| code,
else => 1,
};
}
Terminal window
./runner ls -d /tmp /usr; echo $?
./runner ls /nope; echo $?
./runner nosuch; echo $?

You’ll see:

/tmp
/usr
runner: 'ls' exited with code 0
0
ls: cannot access '/nope': No such file or directory
runner: 'ls' exited with code 2
2
runner: could not start 'nosuch': FileNotFound
127
  • args[1..] is “everything after the runner’s own name”, which is exactly an argv for the child.
  • spawn starts the child and returns right away with a std.process.Child. Your program keeps running while the child does.
  • child.wait(io) blocks until the child ends and returns its Term. Always wait for a child you spawned; it also cleans up what the operating system keeps for it.
  • Returning the child’s exit code from main makes runner behave like the program it ran, so scripts that check $? still work. 127 is what shells use for “command not found”.

If something between spawn and wait can fail, add defer child.kill(io); right after spawn. It stops the child if you leave early, and does nothing once wait has finished.

Two more options you’ll use regularly, and they work the same for run and spawn:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
try init.environ_map.put("GREETING", "hi from the parent");
const result = try std.process.run(gpa, init.io, .{
.argv = &.{ "sh", "-c", "echo \"$GREETING in $(pwd)\"" },
.cwd = .{ .path = "/tmp" },
.environ_map = init.environ_map,
});
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
std.debug.print("{s}", .{result.stdout});
}

You’ll see:

hi from the parent in /tmp
  • .cwd = .{ .path = "/tmp" } runs the child in another folder, without changing yours. Handy for git commands in a specific repository.
  • .environ_map gives the child a specific environment. Here the program adds GREETING to its own copy (from Zig Environment Variables) and passes the whole map on. Leave it out, and the child gets the same environment you got.

You can also feed a child input and read its output yourself. Ask for pipes with .stdin = .pipe and .stdout = .pipe, and the Child gets stdin and stdout fields that are ordinary files you write to and read from. This sends three words to sort:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
var child = try std.process.spawn(io, .{
.argv = &.{"sort"},
.stdin = .pipe,
.stdout = .pipe,
});
defer child.kill(io);
// Send the input, then close stdin so sort knows it has everything.
try child.stdin.?.writeStreamingAll(io, "pear\napple\nfig\n");
child.stdin.?.close(io);
child.stdin = null;
// Read everything sort prints.
var buffer: [1024]u8 = undefined;
var stdout_reader = child.stdout.?.reader(io, &buffer);
const sorted = try stdout_reader.interface.allocRemaining(gpa, .limited(1024 * 1024));
defer gpa.free(sorted);
const term = try child.wait(io);
std.debug.print("{s}sort {f}\n", .{ sorted, term });
}

You’ll see:

apple
fig
pear
sort exited with code 0
  • child.stdin.? is the write end of the child’s stdin. After writing, close it. That’s how sort learns the input has ended; without it, sort waits forever and so does your program. Setting the field to null afterwards tells wait not to close it a second time.
  • child.stdout.? is the read end of its stdout. It’s a normal std.Io.File, so you read it with the same reader as any file (Zig Reading Input).

Two safety options for run are worth knowing:

const result = try std.process.run(gpa, io, .{
.argv = &.{ "some-tool", "--report" },
.stdout_limit = .limited(10 * 1024 * 1024),
.timeout = .{ .duration = .{ .raw = .fromSeconds(30), .clock = .awake } },
});

.stdout_limit (and .stderr_limit) makes run fail with error.StreamTooLong instead of collecting gigabytes of output. .timeout makes it fail with error.Timeout if the child takes too long, and the child is killed. Tested here with sleep 5 and a 1-second timeout, run returned error.Timeout after about a second.

Write a program that runs zig version. If it works, print Zig <version> is installed. If zig can’t be found, print Zig is not in PATH instead of failing.

Hint: catch error.FileNotFound from std.process.run, and trim the newline from stdout.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const result = std.process.run(gpa, init.io, .{
.argv = &.{ "zig", "version" },
}) catch |err| switch (err) {
error.FileNotFound => {
std.debug.print("Zig is not in PATH\n", .{});
return;
},
else => return err,
};
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
if (!result.term.success()) {
std.debug.print("zig version failed: {f}\n", .{result.term});
return;
}
std.debug.print("Zig {s} is installed\n", .{std.mem.trimEnd(u8, result.stdout, "\r\n")});
}
Terminal window
./which-zig
env PATH=/nowhere ./which-zig

You’ll see:

Zig 0.17.1 is installed
Zig is not in PATH

The second command empties PATH, so the lookup fails with FileNotFound. The solution also checks term, because a program that starts and then fails is a different problem.

Run ls -1 / (one name per line) and print how many entries it listed.

Hint: count the '\n' characters in result.stdout with std.mem.countScalar(u8, text, '\n').

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !u8 {
const gpa = init.gpa;
const result = try std.process.run(gpa, init.io, .{ .argv = &.{ "ls", "-1", "/" } });
defer gpa.free(result.stdout);
defer gpa.free(result.stderr);
if (!result.term.success()) {
std.debug.print("ls failed: {s}", .{result.stderr});
return 1;
}
const count = std.mem.countScalar(u8, result.stdout, '\n');
std.debug.print("/ has {d} entries\n", .{count});
return 0;
}

You’ll see something like:

/ has 25 entries

The number depends on your machine. ls -1 prints exactly one line per entry, so counting newlines counts entries.

  • std.process.run(gpa, io, .{ .argv = ... }) runs a program, waits, and returns its stdout, stderr (yours to free) and term.
  • argv is a list: program name first, then each argument. There’s no shell: no *, $VAR, pipes or quoting, and no command injection.
  • Two kinds of failure: the program can’t start (an error like FileNotFound from run/spawn) and it ran and failed (check term, or term.success()).
  • std.process.spawn + child.wait(io) runs a child that shares your terminal. Always wait, and pass the exit code on if it makes sense.
  • .cwd and .environ_map set the child’s folder and environment. .pipe connects its stdin/stdout to your program; close its stdin when you’re done writing.

Next up: Zig Io Interface, what the io value you’ve been passing everywhere actually is.

Quick check

1. You run ls /nope with std.process.run and use try. ls fails. What does try do?
2. What does .argv = &.{ "ls", "*.zig" } do?
3. You pipe data into sort through child.stdin, then read its output, and your program hangs. What did you most likely forget?
4. Which std.process.Child.Term means "the program finished normally and reported success"?