Skip to content
Standard libraryZig 0.17.1Official documentation
Sourcestd/process/Child.zig

Source line 1

Fields

id: ?Id

After wait or kill is called, this becomes null. On Windows this is the hProcess. On POSIX this is the pid.

thread_handle: if (native_os == .windows) std.os.windows.HANDLE else void
stdin: ?File

The writing end of the child process's standard input pipe. Usage requires process.SpawnOptions.StdIo.pipe.

stdout: ?File

The reading end of the child process's standard output pipe. Usage requires process.SpawnOptions.StdIo.pipe.

stderr: ?File

The reading end of the child process's standard error pipe. Usage requires process.SpawnOptions.StdIo.pipe.

resource_usage_statistics: ResourceUsageStatistics = .{}

This is available after calling wait if request_resource_usage_statistics was set to true before calling spawn. TODO move this data into Term

request_resource_usage_statistics: bool

std.process.Child.Allocator

alias

Source line 11

Alias of std.mem.Allocator

std.process.Child.assert

alias

Source line 10

Alias of std.debug.assert

std.process.Child.builtin

constant

Source line 3

std.process.Child.Child

alias

Source line 1

Alias of std.process.Child

std.process.Child.Cwd

container

Source line 117

Fields

inherit

CWD of the child is the same as the current CWD.

dir: Io.Dir

On POSIX systems, fchdir is called after fork using this handle. On Windows, the path is inferred from the provided handle and that path is used when calling CreateProcessW.

path: []const u8

On POSIX systems, chdir is called after fork using this path. On Windows, this path is used when calling CreateProcessW.

std.process.Child.File

alias

Source line 9

Alias of std.Io.File

std.process.Child.Id

type

Source line 13

std.process.Child.Io

alias

Source line 7

Alias of std.Io

std.process.Child.kill

function

Source line 134

Requests for the operating system to forcibly terminate the child process, then blocks until it terminates, then cleans up all resources.

Idempotent and does nothing after wait returns.

Uncancelable. Ignores unexpected errors from the operating system.

pub fn kill(child: *Child, io: Io) void

Parameters

child: *Child
io: Io

std.process.Child.native_os

constant

Source line 4

std.process.Child.process

alias

Source line 8

Alias of std.process

std.process.Child.ResourceUsageStatistics

container

Source line 40

Fields

rusage: @TypeOf(rusage_init) = rusage_init

std.process.Child.ResourceUsageStatistics.getMaxRss

function

Source line 45

Returns the peak resident set size of the child process, in bytes, if available.

pub inline fn getMaxRss(rus: ResourceUsageStatistics) ?usize

Parameters

std.process.Child.ResourceUsageStatistics.rusage_init

constant

Source line 73

std.process.Child.std

alias

Source line 6

Alias of std

std.process.Child.Term

container

Source line 94

Fields

exited: u8
signal: std.posix.SIG
stopped: std.posix.SIG
unknown: u32

std.process.Child.Term.format

function

Source line 107

pub fn format(t: Term, w: *Io.Writer) Io.Writer.Error!void

Parameters

t: Term
w: *Io.Writer

Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

std.process.Child.Term.success

function

Source line 100

pub fn success(t: Term) bool

Parameters

t: Term

std.process.Child.wait

function

Source line 150

Blocks until child process terminates and then cleans up all resources.

pub fn wait(child: *Child, io: Io) WaitError!Term

Parameters

child: *Child
io: Io

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

std.process.Child.WaitError

error-set

Source line 145

Errors

AccessDenied
Canceled Cancelable

Caller has requested the async operation to stop.

Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Source code

std/process/Child.zig

const Child = @This();

const builtin = @import("builtin");
const native_os = builtin.os.tag;

const std = @import("../std.zig");
const Io = std.Io;
const process = std.process;
const File = std.Io.File;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;

pub const Id = switch (native_os) {
    .windows => std.os.windows.HANDLE,
    .wasi => void,
    else => std.posix.pid_t,
};

/// After `wait` or `kill` is called, this becomes `null`.
/// On Windows this is the hProcess.
/// On POSIX this is the pid.
id: ?Id,
thread_handle: if (native_os == .windows) std.os.windows.HANDLE else void,
/// The writing end of the child process's standard input pipe.
/// Usage requires `process.SpawnOptions.StdIo.pipe`.
stdin: ?File,
/// The reading end of the child process's standard output pipe.
/// Usage requires `process.SpawnOptions.StdIo.pipe`.
stdout: ?File,
/// The reading end of the child process's standard error pipe.
/// Usage requires `process.SpawnOptions.StdIo.pipe`.
stderr: ?File,
/// This is available after calling wait if
/// `request_resource_usage_statistics` was set to `true` before calling
/// `spawn`.
/// TODO move this data into `Term`
resource_usage_statistics: ResourceUsageStatistics = .{},
request_resource_usage_statistics: bool,

pub const ResourceUsageStatistics = struct {
    rusage: @TypeOf(rusage_init) = rusage_init,

    /// Returns the peak resident set size of the child process, in bytes,
    /// if available.
    pub inline fn getMaxRss(rus: ResourceUsageStatistics) ?usize {
        switch (native_os) {
            .dragonfly, .freebsd, .netbsd, .openbsd, .illumos, .linux, .serenity => {
                if (rus.rusage) |ru| {
                    return @as(usize, @intCast(ru.maxrss)) * 1024;
                } else {
                    return null;
                }
            },
            .windows => {
                if (rus.rusage) |ru| {
                    return ru.PeakWorkingSetSize;
                } else {
                    return null;
                }
            },
            .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
                if (rus.rusage) |ru| {
                    // Darwin oddly reports in bytes instead of kilobytes.
                    return @as(usize, @intCast(ru.maxrss));
                } else {
                    return null;
                }
            },
            else => return null,
        }
    }

    const rusage_init = switch (native_os) {
        .dragonfly,
        .freebsd,
        .netbsd,
        .openbsd,
        .illumos,
        .linux,
        .serenity,
        .driverkit,
        .ios,
        .maccatalyst,
        .macos,
        .tvos,
        .visionos,
        .watchos,
        => @as(?std.posix.rusage, null),
        .windows => @as(?std.os.windows.PROCESS.VM_COUNTERS, null),
        else => {},
    };
};

pub const Term = union(enum) {
    exited: u8,
    signal: std.posix.SIG,
    stopped: std.posix.SIG,
    unknown: u32,

    pub fn success(t: Term) bool {
        return switch (t) {
            .exited => |code| code == 0,
            else => false,
        };
    }

    pub fn format(t: Term, w: *Io.Writer) Io.Writer.Error!void {
        switch (t) {
            .exited => |code| return w.print("exited with code {d}", .{code}),
            .signal => |sig| return w.print("terminated with signal {t}", .{sig}),
            .stopped => |sig| return w.print("stopped with signal {t}", .{sig}),
            .unknown => return w.writeAll("terminated unexpectedly"),
        }
    }
};

pub const Cwd = union(enum) {
    /// CWD of the child is the same as the current CWD.
    inherit,
    /// On POSIX systems, `fchdir` is called after `fork` using this handle.
    /// On Windows, the path is inferred from the provided handle and that path is used when calling `CreateProcessW`.
    dir: Io.Dir,
    /// On POSIX systems, `chdir` is called after `fork` using this path.
    /// On Windows, this path is used when calling `CreateProcessW`.
    path: []const u8,
};

/// Requests for the operating system to forcibly terminate the child process,
/// then blocks until it terminates, then cleans up all resources.
///
/// Idempotent and does nothing after `wait` returns.
///
/// Uncancelable. Ignores unexpected errors from the operating system.
pub fn kill(child: *Child, io: Io) void {
    if (child.id == null) {
        assert(child.stdin == null);
        assert(child.stdout == null);
        assert(child.stderr == null);
        return;
    }
    io.vtable.childKill(io.userdata, child);
    assert(child.id == null);
}

pub const WaitError = error{
    AccessDenied,
} || Io.Cancelable || Io.UnexpectedError;

/// Blocks until child process terminates and then cleans up all resources.
pub fn wait(child: *Child, io: Io) WaitError!Term {
    assert(child.id != null);
    return io.vtable.childWait(io.userdata, child);
}

test {
    _ = Term;
}