okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221host: ending a child that never started no longer signals the caller's own process group on macOScb73b620a

main
2.3 KiB44 linesraw
1// End a program this host started together with everything that program started (#4529 #4570).
2//
3// Windows: `taskkill /T` walks the tree. Linux and macOS have no such call, and signalling the child alone leaves its own children running (they are
4// re-parented to init). A child started with `detached: ownGroup()` leads a process group of its own, so a signal to the negative pid reaches the
5// whole group and nothing else: the group is the ownership record, no other process (a same-named one included) is ever signalled by name.
6import { spawnSync } from 'node:child_process';
7
8/** The spawn option that makes a child lead its own process group on Linux and macOS (Windows needs none: taskkill /T). */
9export const ownGroup = () => process.platform !== 'win32';
10
11/** Whether the group the child leads still has a member. */
12export function groupAlive(child) {
13  if (process.platform === 'win32' || !child?.pid) return false;
14  try { process.kill(-child.pid, 0); return true; } catch (error) { return error?.code === 'EPERM'; }
15}
16
17/**
18 * Signal the child's whole tree once. A child that does not lead its own group (it was not started with ownGroup()) is signalled alone, which is what
19 * every caller did before.
20 */
21export function endTree(child, signal = 'SIGTERM') {
22  if (!child) return;
23  try {
24    if (process.platform === 'win32') {
25      if (child.pid) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 10000 });
26      return;
27    }
28    if (child.pid) {
29      try { process.kill(-child.pid, signal); return; } catch { /* no such group: it did not lead one, or it is gone */ }
30    }
31    // A child that never started has no pid. On macOS, kill() on it right after a failed spawn signals the caller's own process group (pid 0), so
32    // it is left alone: there is nothing to end.
33    if (child.pid) child.kill(signal);
34  } catch { /* already gone */ }
35}
36
37/** SIGTERM to the tree, then SIGKILL to whatever of its group is still there after `graceMs`. Returns the timer so a caller may clear it. */
38export function endTreeThenKill(child, graceMs = 2000) {
39  endTree(child, 'SIGTERM');
40  if (process.platform === 'win32' || !child?.pid) return null;
41  const timer = setTimeout(() => { if (groupAlive(child)) endTree(child, 'SIGKILL'); }, graceMs);
42  timer.unref?.();
43  return timer;
44}