Skip to main content

Process Management

The std.process module provides functionality for process management, including command-line argument parsing, environment variable handling, and process execution.

Process Control

abort

pub const abort = posix.abort;
Abnormally terminates the current process. Example:
if (critical_error) {
    std.process.abort();
}

exit

pub const exit = posix.exit;
Terminates the process with a status code. Example:
std.process.exit(0); // Success
std.process.exit(1); // Failure

Working Directory

changeCurDir

pub const changeCurDir = posix.chdir;
Changes the current working directory.

changeCurDirZ

pub const changeCurDirZ = posix.chdirZ;
Changes the current working directory (null-terminated path).

getCwd

pub fn getCwd(out_buffer: []u8) GetCwdError![]u8
Gets the current working directory.
out_buffer
[]u8
required
Buffer to store the current directory path
return
[]u8
Slice of the buffer containing the path (from index 0)
  • Windows: WTF-8 encoded
  • Other: Opaque byte sequence
Example:
var buf: [std.fs.max_path_bytes]u8 = undefined;
const cwd = try std.process.getCwd(&buf);
std.debug.print("CWD: {s}\n", .{cwd});

getCwdAlloc

pub fn getCwdAlloc(allocator: Allocator) GetCwdAllocError![]u8
Gets the current working directory, allocating memory for the result.
allocator
Allocator
required
Allocator for the result
return
[]u8
Caller must free the returned memory
  • Windows: WTF-8 encoded
  • Other: Opaque byte sequence
Example:
const cwd = try std.process.getCwdAlloc(allocator);
defer allocator.free(cwd);

Environment Variables

EnvMap

pub const EnvMap = struct {
    hash_map: HashMap,
    // ...
}
A hash map for storing environment variables. On Windows, keys are case-insensitive.

EnvMap.init

pub fn init(allocator: Allocator) EnvMap
Creates a new EnvMap.
allocator
Allocator
required
Allocator for the map and string storage

EnvMap.deinit

pub fn deinit(self: *EnvMap) void
Frees all stored keys and values, and the backing storage.

EnvMap.put

pub fn put(self: *EnvMap, key: []const u8, value: []const u8) !void
Inserts or updates an environment variable. Key and value are copied.
key
[]const u8
required
Environment variable name (must be valid WTF-8 on Windows)
value
[]const u8
required
Environment variable value
Example:
var env = EnvMap.init(allocator);
defer env.deinit();
try env.put("PATH", "/usr/bin:/bin");

EnvMap.putMove

pub fn putMove(self: *EnvMap, key: []u8, value: []u8) !void
Like put but transfers ownership of key and value to the EnvMap.

EnvMap.get

pub fn get(self: EnvMap, key: []const u8) ?[]const u8
Returns the value for a key, or null if not found.
key
[]const u8
required
Environment variable name (must be valid WTF-8 on Windows)
return
?[]const u8
Value if found, null otherwise. Invalidated if the key is removed.
Example:
if (env.get("HOME")) |home| {
    std.debug.print("Home: {s}\n", .{home});
}

EnvMap.remove

pub fn remove(self: *EnvMap, key: []const u8) void
Removes an environment variable and frees its memory.

EnvMap.count

pub fn count(self: EnvMap) HashMap.Size
Returns the number of environment variables.

EnvMap.iterator

pub fn iterator(self: *const EnvMap) HashMap.Iterator
Returns an iterator over the environment variables. Example:
var it = env.iterator();
while (it.next()) |entry| {
    std.debug.print("{s}={s}\n", .{ entry.key_ptr.*, entry.value_ptr.* });
}

EnvMap.clone

pub fn clone(em: *const EnvMap, gpa: Allocator) Allocator.Error!EnvMap
Creates a full copy of the EnvMap.

getEnvMap

pub fn getEnvMap(allocator: Allocator) GetEnvMapError!EnvMap
Returns a snapshot of the current process’s environment variables.
allocator
Allocator
required
Allocator for the EnvMap and strings
return
EnvMap
Caller owns the result and must call deinit() when done. Modifications do not affect the actual environment.
Example:
var env = try std.process.getEnvMap(allocator);
defer env.deinit();

if (env.get("PATH")) |path| {
    std.debug.print("PATH: {s}\n", .{path});
}

getEnvVarOwned

pub fn getEnvVarOwned(allocator: Allocator, key: []const u8) GetEnvVarOwnedError![]u8
Gets a single environment variable, allocating memory for the result.
allocator
Allocator
required
Allocator for the result
key
[]const u8
required
Environment variable name (must be valid WTF-8 on Windows)
return
[]u8
Caller must free the returned memory
  • Windows: WTF-8 encoded
  • Other: Opaque byte sequence
Errors:
  • error.EnvironmentVariableNotFound - Variable does not exist
  • error.InvalidWtf8 - Key is not valid WTF-8 (Windows only)
Example:
const home = try std.process.getEnvVarOwned(allocator, "HOME");
defer allocator.free(home);

hasEnvVar

pub fn hasEnvVar(allocator: Allocator, key: []const u8) HasEnvVarError!bool
Checks if an environment variable exists. Example:
if (try std.process.hasEnvVar(allocator, "DEBUG")) {
    // Enable debug mode
}

hasEnvVarConstant

pub fn hasEnvVarConstant(comptime key: []const u8) bool
Checks if a compile-time known environment variable exists (no allocation needed). Example:
if (std.process.hasEnvVarConstant("CI")) {
    // Running in CI environment
}

parseEnvVarInt

pub fn parseEnvVarInt(comptime key: []const u8, comptime I: type, base: u8) ParseEnvVarIntError!I
Parses an environment variable as an integer.
key
[]const u8
required
Environment variable name (must be valid WTF-8 on Windows)
I
type
required
Integer type to parse to
base
u8
required
Number base (2-36)
Example:
const port = try std.process.parseEnvVarInt("PORT", u16, 10);

Command-Line Arguments

ArgIterator

pub const ArgIterator = struct {
    inner: InnerType,
    // ...
}
Cross-platform command-line argument iterator.

ArgIterator.init

pub fn init() ArgIterator
Initializes the argument iterator (POSIX only). Note: On Windows and WASI, use initWithAllocator instead.

ArgIterator.initWithAllocator

pub fn initWithAllocator(allocator: Allocator) InitError!ArgIterator
Initializes the argument iterator with an allocator (required on Windows/WASI).
allocator
Allocator
required
Allocator for internal buffers
Example:
var args = try std.process.ArgIterator.initWithAllocator(allocator);
defer args.deinit();

ArgIterator.next

pub fn next(self: *ArgIterator) ?[:0]const u8
Gets the next argument.
return
?[:0]const u8
Next argument, or null at the end
  • Windows: WTF-8 encoded
  • Other: Opaque byte sequence
Example:
var args = try std.process.ArgIterator.initWithAllocator(allocator);
defer args.deinit();

while (args.next()) |arg| {
    std.debug.print("Arg: {s}\n", .{arg});
}

ArgIterator.skip

pub fn skip(self: *ArgIterator) bool
Skips the next argument without capturing it.
return
bool
true if an argument was skipped, false if at the end

ArgIterator.deinit

pub fn deinit(self: *ArgIterator) void
Frees internal buffers (required on Windows/WASI).

args

pub fn args() ArgIterator
Returns an argument iterator (POSIX only).

argsWithAllocator

pub fn argsWithAllocator(allocator: Allocator) ArgIterator.InitError!ArgIterator
Returns an argument iterator (cross-platform). Example:
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();

argsAlloc

pub fn argsAlloc(allocator: Allocator) ![][:0]u8
Allocates and returns all arguments as a slice.
return
[][:0]u8
Caller must call argsFree() when done
  • Windows: WTF-8 encoded
  • Other: Opaque byte sequence
Example:
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);

for (args, 0..) |arg, i| {
    std.debug.print("Arg {}: {s}\n", .{ i, arg });
}

argsFree

pub fn argsFree(allocator: Allocator, args_alloc: []const [:0]u8) void
Frees memory allocated by argsAlloc.

Argument Parsing

ArgIteratorGeneral

pub fn ArgIteratorGeneral(comptime options: ArgIteratorGeneralOptions) type
A general-purpose argument iterator with customizable parsing.

ArgIteratorGeneralOptions

pub const ArgIteratorGeneralOptions = struct {
    comments: bool = false,
    single_quotes: bool = false,
};
comments
bool
default:"false"
Enable # comment support
single_quotes
bool
default:"false"
Enable single quote parsing
Example:
const Iterator = std.process.ArgIteratorGeneral(.{
    .comments = true,
    .single_quotes = true,
});

var iter = try Iterator.init(allocator, cmd_line);
defer iter.deinit();

while (iter.next()) |arg| {
    std.debug.print("{s}\n", .{arg});
}

ArgIteratorWindows

pub const ArgIteratorWindows = struct { ... }
Windows command-line parsing compatible with the post-2008 C runtime. Parsing Rules:
  • 2n backslashes + quote → emit n backslashes, toggle quote mode
  • 2n+1 backslashes + quote → emit n backslashes + literal quote
  • n backslashes (no quote) → emit n backslashes
  • Spaces/tabs end arguments (unless in quotes)

Child Process

pub const Child = @import("process/Child.zig");
Provides functionality for spawning and managing child processes.

Error Sets

GetCwdError

pub const GetCwdError = posix.GetCwdError;

GetEnvMapError

pub const GetEnvMapError = error{
    OutOfMemory,
    Unexpected, // WASI only
};

GetEnvVarOwnedError

pub const GetEnvVarOwnedError = error{
    OutOfMemory,
    EnvironmentVariableNotFound,
    InvalidWtf8, // Windows only
};

Usage Patterns

Complete Argument Processing

const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var args = try std.process.argsWithAllocator(allocator);
    defer args.deinit();

    // Skip program name
    _ = args.skip();

    while (args.next()) |arg| {
        if (std.mem.eql(u8, arg, "--help")) {
            std.debug.print("Usage: ...\n", .{});
            std.process.exit(0);
        }
    }
}

Environment Variable Management

pub fn loadConfig(allocator: Allocator) !Config {
    const port = std.process.parseEnvVarInt("PORT", u16, 10) catch 8080;
    
    const host = std.process.getEnvVarOwned(allocator, "HOST") catch |err| switch (err) {
        error.EnvironmentVariableNotFound => try allocator.dupe(u8, "localhost"),
        else => return err,
    };
    errdefer allocator.free(host);

    return Config{ .host = host, .port = port };
}

Build docs developers (and LLMs) love