WATCHDOG
The watchdog's program: reads +<pid> (kept) and -<pid> (ended) lines; when what it reads ends (the process that
started it has), stops those still running: SIGTERM, then SIGKILL after 5 seconds.
export const WATCHDOG = ` const pids = new Set(); let buf = ""; process.stdin.setEncoding("utf8"); process.stdin.on("data", (d) => { buf += d; for (let i; (i = buf.indexOf("\\n")) >= 0; buf = buf.slice(i + 1)) { const line = buf.slice(0, i); if (line[0] === "+") pids.add(Number(line.slice(1))); else pids.delete(Number(line.slice(1))); } }); const signal = (s) => { for (const p of pids) try { process.kill(p, s); } catch { pids.delete(p); } }; let stopping = false; const stop = () => { if (stopping) return; stopping = true; signal("SIGTERM"); const until = Date.now() + 5000; setInterval(() => { signal(0); if (pids.size && Date.now() > until) signal("SIGKILL"); if (!pids.size || Date.now() > until) process.exit(0); }, 100); }; process.stdin.on("end", stop); process.stdin.on("close", stop); process.stdin.on("error", stop); `