Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/+kill-group.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`proc.killGroup(pgid, sig)` sends a signal to the process group that `Options.pgid_out` published, or to the child itself while it has not made that group yet, as `proc.run` does. It makes only kill system calls and does not wait, so a signal handler can call it; `proc.stopGroup` also waits for the group to go.
48 changes: 30 additions & 18 deletions src/proc.zig
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ pub const Options = struct {
/// when true, the child's group is killed and `error.Canceled` returned.
cancel: ?*const std.atomic.Value(bool) = null,
/// Set to the child's process group id while it runs, 0 otherwise, so a
/// signal handler can kill it with `stopGroup`. It is set before the
/// child has made the group, which a kill of the group alone then
/// misses. Only with `new_session`.
/// signal handler can kill it with `killGroup` or `stopGroup`. It is set
/// before the child has made the group, which a kill of the group alone
/// then misses. Only with `new_session`.
pgid_out: ?*std.atomic.Value(i32) = null,
/// `truncate`: stdout past `stdout_limit` is read and dropped, and the
/// call goes on; `fail`: it is an error and the child is killed.
Expand Down Expand Up @@ -223,13 +223,29 @@ pub fn groupAlive(pgid: linux.pid_t) bool {
}
}

/// SIGKILL the group `pgid`, or process `pgid` itself while it has not made
/// that group yet, and wait (up to 10 s) until no member of the group is
/// alive. Only system calls and stack buffers, so a signal handler may call
/// it, with the pgid that `Options.pgid_out` published.
/// Send `sig` to the process group `pgid` of a child that `run` started in
/// a new session, as `Options.pgid_out` publishes it. The child makes that
/// group with setsid after the fork, so until then there is no such group:
/// the child itself is signalled, as it has started nothing before it
/// execs, and then the group again in case it was made meanwhile. The child
/// is reaped only after pgid_out is cleared, so a published pid is still
/// the child's. A `pgid` of 0 or less does nothing: 0 is pgid_out's "no
/// child", which kill would take for this process's own group. Safe in a
/// signal handler: only kill system calls, and no waiting; `stopGroup`
/// also waits until the group is gone.
pub fn killGroup(pgid: linux.pid_t, sig: linux.SIG) void {
if (pgid <= 0) return;
if (linux.errno(linux.kill(-pgid, sig)) != .SRCH) return;
_ = linux.kill(pgid, sig);
_ = linux.kill(-pgid, sig);
}

/// `killGroup(pgid, .KILL)`, then wait (up to 10 s) until no member of the
/// group is alive. Only system calls and stack buffers, so a signal handler
/// may call it, with the pgid that `Options.pgid_out` published.
pub fn stopGroup(pgid: linux.pid_t) void {
if (pgid <= 0) return;
kill(pgid, true, .KILL);
killGroup(pgid, .KILL);
waitGroupGone(pgid);
}

Expand All @@ -238,20 +254,16 @@ pub fn stopGroup(pgid: linux.pid_t) void {
fn waitGroupGone(pgid: linux.pid_t) void {
const until = nowMs() + 10_000;
while (groupAlive(pgid) and nowMs() < until) {
kill(pgid, true, .KILL);
killGroup(pgid, .KILL);
var ts: linux.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
_ = linux.nanosleep(&ts, null);
}
}

/// Signal the child `pid`, or with `group` its process group. The child
/// makes that group with setsid after the fork, so until then there is no
/// such group: the child itself is signalled, as it has started nothing
/// before it execs, and then the group again in case it was made meanwhile.
/// Signal the child `pid`, or with `group` its process group.
fn kill(pid: linux.pid_t, group: bool, sig: linux.SIG) void {
if (group and linux.errno(linux.kill(-pid, sig)) != .SRCH) return;
if (group) return killGroup(pid, sig);
_ = linux.kill(pid, sig);
if (group) _ = linux.kill(-pid, sig);
}

const Pipe = struct { r: sys.fd_t, w: sys.fd_t };
Expand Down Expand Up @@ -404,7 +416,7 @@ pub fn run(gpa: Allocator, exe: []const u8, argv: []const []const u8, envp: Envp
if (opts.end_with_leader and opts.new_session and exitedWithin(pid, 0)) {
// The child is gone: stop its group, keep what is already in
// the pipes, and close them under any writer that left it.
kill(pid, true, .KILL);
killGroup(pid, .KILL);
for (fds[1..], 1..) |fd, i| {
if (fd < 0) continue;
setNonblock(fd);
Expand Down Expand Up @@ -497,15 +509,15 @@ pub fn run(gpa: Allocator, exe: []const u8, argv: []const []const u8, envp: Envp
kill(pid, opts.new_session, .TERM);
if (!exitedWithin(pid, opts.grace_ms)) kill(pid, opts.new_session, .KILL);
}
if (opts.new_session) kill(pid, true, .KILL);
if (opts.new_session) killGroup(pid, .KILL);
if (opts.new_session and opts.wait_for_group) waitGroupGone(pid);
if (opts.pgid_out) |o| o.store(0, .seq_cst);
_ = reap(pid) catch null;
return err;
}
// Members of the child's group outliving it are not ours to keep; the
// unreaped leader keeps the group id from being reused until this is sent.
if (opts.new_session) kill(pid, true, .KILL);
if (opts.new_session) killGroup(pid, .KILL);
if (opts.new_session and opts.wait_for_group) waitGroupGone(pid);
if (opts.pgid_out) |o| o.store(0, .seq_cst);
const term = try reap(pid);
Expand Down
72 changes: 72 additions & 0 deletions src/proc_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,78 @@ test "stopGroup on a pgid as soon as it is published kills the child" {
}
}

var kill_pgid = std.atomic.Value(i32).init(0);
var winches = std.atomic.Value(u32).init(0);

fn onUsr2KillGroup(_: linux.SIG) callconv(.c) void {
proc.killGroup(kill_pgid.load(.seq_cst), .KILL);
}

fn onWinch(_: linux.SIG) callconv(.c) void {
_ = winches.fetchAdd(1, .seq_cst);
}

fn signalWhenStarted(root: []const u8, tid: linux.pid_t) void {
for (0..1000) |_| {
if (readPid(root, "background") != null) break;
sleepMs(10);
}
_ = linux.tgkill(linux.getpid(), tid, .USR2);
}

/// Child `pid`, forked by the test, ends by SIGKILL within a second; one
/// that does not is killed, so it cannot outlive the test.
fn expectKilled(pid: linux.pid_t) !void {
var status: u32 = 0;
for (0..100) |_| {
if (linux.wait4(pid, @ptrCast(&status), linux.W.NOHANG, null) == @as(usize, @intCast(pid))) {
return testing.expectEqual(@as(u32, 9), status & 0x7f);
}
sleepMs(10);
}
_ = linux.kill(pid, .KILL);
_ = linux.wait4(pid, @ptrCast(&status), 0, null);
return error.TestUnexpectedResult;
}

test "killGroup in a signal handler kills a child before and after it has made its group" {
const root = begin();
defer end(root);
var prev_usr2: linux.Sigaction = undefined;
const on_usr2: linux.Sigaction = .{ .handler = .{ .handler = &onUsr2KillGroup }, .mask = linux.sigemptyset(), .flags = 0 };
_ = linux.sigaction(.USR2, &on_usr2, &prev_usr2);
defer _ = linux.sigaction(.USR2, &prev_usr2, null);
var prev_winch: linux.Sigaction = undefined;
const on_winch: linux.Sigaction = .{ .handler = .{ .handler = &onWinch }, .mask = linux.sigemptyset(), .flags = 0 };
_ = linux.sigaction(.WINCH, &on_winch, &prev_winch);
defer _ = linux.sigaction(.WINCH, &prev_winch, null);
const tid = linux.gettid();

// pgid_out's 0, no child, is not this process's own group.
proc.killGroup(0, .WINCH);
try testing.expectEqual(@as(u32, 0), winches.load(.seq_cst));

// Between fork and setsid the child is in this process's group and no
// group has its pid for id, so only a kill of the child itself reaches it.
const child: isize = @bitCast(linux.fork());
if (child == 0) {
sleepMs(30_000);
linux.exit_group(0);
}
try testing.expect(child > 0);
kill_pgid.store(@intCast(child), .seq_cst);
_ = linux.tgkill(linux.getpid(), tid, .USR2);
try expectKilled(@intCast(child));

// Once it has made the group, all of it, here while run waits on it.
kill_pgid.store(0, .seq_cst);
const thread = try std.Thread.spawn(.{}, signalWhenStarted, .{ root, tid });
const r = sh(root, "sleep 30 >/dev/null &\necho $! > background\nsleep 30\n", .{ .pgid_out = &kill_pgid });
thread.join();
try expectGone(root, "background");
try testing.expectEqual(@as(u32, 128 + 9), (try r).term.code());
}

test "stdin to a child that does not read it fails with EPIPE, not SIGPIPE" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
Expand Down
Loading