Search code examples
czig

Idiomatic alternative to C's `system` function in Zig


Is there a way to make a system call in Zig, other than using a cImport? right now I've got it to work with something like that:

const c = @cImport({
    @cInclude("stdlib.h");
});

// ...

const result: c_int = c.system(cmd);

While this works fine, I'd like to do it "the zig way", without having to import stuff from C.


Solution

  • The alternative to using C's system() function is to use ChildProcess in Zig:

    const std = @import("std");
    
    pub fn main() !void {
        var gpa = std.heap.GeneralPurposeAllocator(.{}){};
        defer std.debug.assert(gpa.deinit() == .ok);
        const allocator = gpa.allocator();
    
        const result = try std.ChildProcess.exec(.{
            .allocator = allocator,
            .argv = &[_][]const u8{ "date" },
        });
        defer {
            allocator.free(result.stdout);
            allocator.free(result.stderr);
        }
    
        std.log.info("stdout: {s}", .{ result.stdout });
        std.log.info("stderr: {s}", .{ result.stderr });
    }
    

    This prints:

    $ zig build run
    info: stdout: Tue, Aug  8, 2023  1:45:02 PM
    
    info: stderr: