Skip to content

Commit 384ff92

Browse files
committed
fix: write exit code after process exits in terminate command
The EXIT trap in the process writes $? (which is 0 for SIGTERM) and would overwrite our exit code if we wrote it immediately. Now we wait for the process to exit before writing 143 (SIGTERM) or 137 (SIGKILL).
1 parent df15f39 commit 384ff92

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

src/node/runtime/backgroundCommands.test.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -135,12 +135,8 @@ describe("backgroundCommands", () => {
135135
expect(result).toContain("sleep 2");
136136
expect(result).toContain("kill -0 1234");
137137
expect(result).toContain("kill -9 -1234 2>/dev/null || true");
138-
});
139-
140-
it("writes exit code 137 on force kill", () => {
141-
const result = buildTerminateCommand(1234, "/tmp/exit_code");
142-
143-
expect(result).toContain("echo 137 > '/tmp/exit_code'");
138+
expect(result).toContain("echo 137 >"); // SIGKILL exit code
139+
expect(result).toContain("echo 143 >"); // SIGTERM exit code (written after process exits)
144140
});
145141

146142
it("quotes exit code path with spaces", () => {

src/node/runtime/backgroundCommands.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,17 @@ export function buildTerminateCommand(
133133
quotePath: (p: string) => string = shellQuote
134134
): string {
135135
const negPid = -pid; // Negative PID targets process group (PID === PGID due to set -m)
136+
// Send SIGTERM, wait for process to exit, then write the correct exit code.
137+
// We can't write immediately because the process's EXIT trap would overwrite it.
138+
// After sleep 2, either the process exited (write SIGTERM code) or we escalate to SIGKILL.
136139
return (
137140
`kill -15 ${negPid} 2>/dev/null || true; ` +
138141
`sleep 2; ` +
139142
`if kill -0 ${pid} 2>/dev/null; then ` +
140143
`kill -9 ${negPid} 2>/dev/null || true; ` +
141144
`echo ${EXIT_CODE_SIGKILL} > ${quotePath(exitCodePath)}; ` +
145+
`else ` +
146+
`echo ${EXIT_CODE_SIGTERM} > ${quotePath(exitCodePath)}; ` +
142147
`fi`
143148
);
144149
}

0 commit comments

Comments
 (0)