Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopExitChildren.ts

70 lines2.2 KB

1// @effect-diagnostics nodeBuiltinImport:off - Runs synchronously in the process "exit" event, where nothing async completes.
2import * as NodeFS from "node:fs";
3​
4// Matches the backend's quit budget: SIGTERM, 5 s grace, SIGKILL, 1 s wait.
5const TERMINATE_GRACE_MS = 5_000;
6const KILL_WAIT_MS = 1_000;
7​
8const readProc = (path: string): string | undefined => {
9 try {
10 return NodeFS.readFileSync(path, "utf8");
11 } catch {
12 return undefined;
13 }
14};
15​
16// Chromium launches helpers from its own threads, so each thread's children file is read.
17const childPids = (pid: number): ReadonlyArray<number> => {
18 let tasks: ReadonlyArray<string>;
19 try {
20 tasks = NodeFS.readdirSync(`/proc/${pid}/task`);
21 } catch {
22 return [];
23 }
24 return tasks.flatMap((task) =>
25 (readProc(`/proc/${pid}/task/${task}/children`) ?? "")
26 .split(" ")
27 .filter((value) => value.trim() !== "")
28 .map(Number),
29 );
30};
31​
32// A zombie has already released its memory mappings.
33const isRunning = (pid: number): boolean => {
34 const stat = readProc(`/proc/${pid}/stat`);
35 if (stat === undefined) return false;
36 const state = stat.charAt(stat.lastIndexOf(")") + 2);
37 return state !== "Z" && state !== "X";
38};
39​
40const signal = (pids: ReadonlyArray<number>, name: NodeJS.Signals) => {
41 for (const pid of pids) {
42 try {
43 process.kill(pid, name);
44 } catch {}
45 }
46};
47​
48const waitUntilStopped = (pids: ReadonlyArray<number>, maxMs: number): ReadonlyArray<number> => {
49 const tick = new Int32Array(new SharedArrayBuffer(4));
50 let running = pids.filter(isRunning);
51 for (let waited = 0; waited < maxMs && running.length > 0; waited += 10) {
52 Atomics.wait(tick, 0, 0, 10);
53 running = running.filter(isRunning);
54 }
55 return running;
56};
57​
58/**
59 * Stops the main process's children while it is still alive. On an AppImage the image unmounts
60 * as soon as main exits, so children left running then die with SIGBUS. Linux only (/proc).
61 * Returns the pids that needed SIGKILL.
62 */
63export const stopChildProcessesBeforeExit = (pid: number): ReadonlyArray<number> => {
64 const children = childPids(pid);
65 signal(children, "SIGTERM");
66 const survivors = waitUntilStopped(children, TERMINATE_GRACE_MS);
67 signal(survivors, "SIGKILL");
68 waitUntilStopped(survivors, KILL_WAIT_MS);
69 return survivors;
70};