In this blog we will continue modifying last program. We will listen to the exit code and log it to console.
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();
std.process.exit(1);
} 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" };
var child = try std.process.spawn(init.io, .{ .argv = argv, .stdout = .inherit });
const term = try child.wait(init.io);
switch (term) {
.exited => |code| {
try stdout_writer.print("Main: Child exit code is {}\n", .{code});
},
.signal => |sig| {
try stdout_writer.print("Main: OS killed child with {}\n", .{sig});
},
.stopped => |signal| {
try stdout_writer.print("Main: child got stopped/suspended by signal {}\n", .{signal});
},
.unknown => |code| {
try stdout_writer.print("Main: child got terminated abnormally with raw code {}\n", .{code});
},
}
try stdout_writer.flush();
}
}
We'll build using zig build-exe -O ReleaseSafe worker__main.zig and run using ./worker__main. The output will be
Printing from main process...
Printing from worker process...
Main: Child exit code is 1
Thanks for reading. To be continued,
Top comments (0)