okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cb73b620a
main
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 ) { 13if ( process . platform === 'win32' || ! child ?. pid ) return false ; 14try { 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' ) { 22if ( ! child ) return ; 23try { 24if ( process . platform === 'win32' ) { 25if ( child . pid ) spawnSync ( 'taskkill' , [ '/PID' , String ( child . pid ), '/T' , '/F' ], { windowsHide :true , stdio :'ignore' , timeout :10000 }); 26return ; 27} 28if ( child . pid ) { 29try { 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. 33if ( 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 ) { 39endTree ( child , 'SIGTERM' ); 40if ( process . platform === 'win32' || ! child ?. pid ) return null ; 41const timer = setTimeout (() => { if ( groupAlive ( child )) endTree ( child , 'SIGKILL' ); }, graceMs ); 42timer . unref ?.(); 43return timer ; 44}