//! Child process helpers: spawn a job's command with logs redirected into its job directory, //! signal its process group, and probe liveness. POSIX only for now (Windows is deferred). const std = @import("std"); const builtin = @import("builtin"); const Io = std.Io; const Dir = Io.Dir; const File = Io.File; const posix = std.posix; pub const Pid = posix.pid_t; pub const SpawnError = std.process.SpawnError || File.OpenError; /// Opens `sub_path` for appending (creating it if needed) so retries accumulate in one log. pub fn openAppend(io: Io, dir: Dir, sub_path: []const u8) !File { var file = try dir.createFile(io, sub_path, .{ .truncate = false }); errdefer file.close(io); seekToEnd(file); return file; } fn seekToEnd(file: File) void { switch (builtin.os.tag) { .windows, .wasi => {}, .linux => _ = std.os.linux.lseek(file.handle, 0, std.os.linux.SEEK.END), else => _ = std.c.lseek(file.handle, 0, std.c.SEEK.END), } } /// Spawns `command` (no shell) in `work_dir`, appending stdout/stderr to `logs/stdout.log` and /// `logs/stderr.log` under `job_dir`. The child leads its own process group so the whole tree /// can be signalled. Returns the child; the caller must `wait` or `kill` it. pub fn spawnJob(io: Io, job_dir: Dir, command: []const []const u8) SpawnError!std.process.Child { var work = try job_dir.openDir(io, "work", .{}); defer work.close(io); var out = try openAppend(io, job_dir, "logs/stdout.log"); defer out.close(io); var err = try openAppend(io, job_dir, "logs/stderr.log"); defer err.close(io); return std.process.spawn(io, .{ .argv = command, .cwd = .{ .dir = work }, .stdin = .ignore, .stdout = .{ .file = out }, .stderr = .{ .file = err }, .pgid = 0, }); } /// Appends a line to a log file (used to record spawn failures in `stderr.log`). pub fn appendLog(io: Io, job_dir: Dir, sub_path: []const u8, line: []const u8) !void { var f = try openAppend(io, job_dir, sub_path); defer f.close(io); try f.writeStreamingAll(io, line); try f.writeStreamingAll(io, "\n"); } pub fn currentPid() i64 { return switch (builtin.os.tag) { .linux => std.os.linux.getpid(), .windows, .wasi => 0, else => std.c.getpid(), }; } pub const Signal = enum { term, kill }; /// Signals the process group led by `pid`, falling back to the single process. pub fn signalTree(pid: Pid, sig: Signal) void { if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return; const s: posix.SIG = switch (sig) { .term => .TERM, .kill => .KILL, }; posix.kill(-pid, s) catch |e| switch (e) { error.ProcessNotFound => posix.kill(pid, s) catch {}, else => {}, }; } /// True if a process with this pid exists (even if owned by another user). pub fn isAlive(pid: i64) bool { if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return false; const p = std.math.cast(Pid, pid) orelse return false; if (p <= 0) return false; posix.kill(p, @enumFromInt(0)) catch |e| switch (e) { error.ProcessNotFound => return false, else => return true, }; return true; } /// Maps a wait result to a shell-style exit code: signals become `128 + signal`. pub fn exitCodeOf(term: std.process.Child.Term) i32 { return switch (term) { .exited => |c| c, .signal => |s| 128 + @as(i32, @intCast(@intFromEnum(s))), .stopped => |s| 128 + @as(i32, @intCast(@intFromEnum(s))), .unknown => |u| @intCast(@min(u, 255)), }; } fn readAll(io: Io, dir: Dir, sub_path: []const u8) ![]u8 { return dir.readFileAlloc(io, sub_path, std.testing.allocator, .limited(1 << 16)); } fn makeJobDir(io: Io, tmp: *std.testing.TmpDir) !Dir { try tmp.dir.createDirPath(io, "work"); try tmp.dir.createDirPath(io, "logs"); return tmp.dir; } test "spawnJob redirects stdout and stderr and runs in work/" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try makeJobDir(io, &tmp); var child = try spawnJob(io, dir, &.{ "sh", "-c", "echo out; echo err >&2; pwd > where; exit 3" }); const term = try child.wait(io); try std.testing.expectEqual(@as(i32, 3), exitCodeOf(term)); const out = try readAll(io, dir, "logs/stdout.log"); defer std.testing.allocator.free(out); try std.testing.expectEqualStrings("out\n", out); const err = try readAll(io, dir, "logs/stderr.log"); defer std.testing.allocator.free(err); try std.testing.expectEqualStrings("err\n", err); _ = try dir.statFile(io, "work/where", .{}); } test "logs append across runs" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try makeJobDir(io, &tmp); for (0..2) |_| { var child = try spawnJob(io, dir, &.{ "echo", "line" }); _ = try child.wait(io); } const out = try readAll(io, dir, "logs/stdout.log"); defer std.testing.allocator.free(out); try std.testing.expectEqualStrings("line\nline\n", out); } test "spawn failure is reported" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try makeJobDir(io, &tmp); try std.testing.expectError(error.FileNotFound, spawnJob(io, dir, &.{"/definitely/not/a/binary"})); } test "signalTree kills the whole process group" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try makeJobDir(io, &tmp); // The shell forks a background sleeper that records its pid, then waits. var child = try spawnJob(io, dir, &.{ "sh", "-c", "sleep 30 & echo $! > grandchild; wait" }); const pid = child.id.?; var tries: usize = 0; while (tries < 200) : (tries += 1) { _ = dir.statFile(io, "work/grandchild", .{}) catch { try io.sleep(.fromMilliseconds(10), .real); continue; }; break; } const raw = try readAll(io, dir, "work/grandchild"); defer std.testing.allocator.free(raw); const grandchild = try std.fmt.parseInt(i64, std.mem.trim(u8, raw, "\n "), 10); try std.testing.expect(isAlive(grandchild)); signalTree(pid, .kill); const term = try child.wait(io); try std.testing.expectEqual(@as(i32, 137), exitCodeOf(term)); // Allow the kernel to reap the orphaned sleeper. tries = 0; while (isAlive(grandchild) and tries < 200) : (tries += 1) try io.sleep(.fromMilliseconds(10), .real); try std.testing.expect(!isAlive(grandchild)); } test "isAlive" { try std.testing.expect(isAlive(currentPid())); try std.testing.expect(!isAlive(-1)); try std.testing.expect(!isAlive(0)); }