You have been zigged (series) : Forking a child process

Published: (June 19, 2026 at 10:09 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

This program is about the POSIX fork() syscall. Zig favors standard library functions std.process.spawn() and std.process.run() functions instead of using OS specific functions like fork(). The spawn and run functions use appropriate OS specific functions underneath and the code we write can stay OS agnostic. As we already saw the spawn function in blog 13, let’s look at run function in this blog. The run function allows the programmer to have more control over the child process than spawn. Lets use it to run another process of the same executable. There are several reasons why one would want to do this.

  • Fault isolation

  • Security sandboxing

  • True hard memory limits

Lets see the code for a program that spins itself up on startup as a worker.

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const allocator = init.arena.allocator();
    // defer init.arena.deinit();  not needed as zig will deinit main arena on exit anyway
    const args = try init.minimal.args.toSlice(allocator);
    if (args.len == 2 and std.mem.eql(u8, args[1], "--worker=true")) {
        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("Printing from worker process...\n\n", .{});
        try stdout_writer.flush();
    } else {
        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("Printing from main process...\n\n", .{});
        try stdout_writer.flush();

        const argv = &.{ "./worker__main", "--worker=true" };
        _ = try std.process.spawn(init.io, .{ .argv = argv, .stdout = .inherit });
    }
}
Enter fullscreen mode


Exit fullscreen mode

We can build executable using zig build-exe -O ReleaseSafe worker__main.zig, which will create worker__main. When we execute it using ./worker__main, we ll see

Printing from main process...

Printing from worker process...
Enter fullscreen mode


Exit fullscreen mode

Thanks for reading. To be continued.

0 views
Back to Blog

Related posts

Read more »

Speculative Decoding on Mobile GPUs

--- title: 'Speculative Decoding on Mobile GPUs: Draft-Verify LLM Pipelines with Vulkan Compute' published: true description: 'Build a speculative decoding pipe...