Skip to content

Commit f9ef820

Browse files
committed
fix(hub): terminate child process trees on POSIX
1 parent 581670f commit f9ef820

2 files changed

Lines changed: 58 additions & 11 deletions

File tree

‎packages/hub/src/node/__tests__/host-terminals.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,34 @@ describe('devframeTerminalHost stream lifecycle', () => {
309309
expect(result.exitCode).toBe(0)
310310
})
311311

312+
it.skipIf(process.platform === 'win32')('terminates the subprocess started by a running command', async () => {
313+
const { host } = createTerminalHost()
314+
const session = await host.startChildProcess({
315+
command: NODE,
316+
args: ['-e', `require('node:child_process').spawn(process.execPath, ['-e', 'process.stdout.write(String(process.pid)); setInterval(() => {}, 1000)'], { stdio: 'inherit' })`],
317+
}, { id: 'tree', title: 'Tree' })
318+
const result = session.getResult()
319+
let pid = 0
320+
try {
321+
await waitUntil(() => {
322+
pid = Number(session.buffer?.join('').trim())
323+
expect(pid).toBeGreaterThan(0)
324+
}, 5000)
325+
await session.terminate()
326+
await waitUntil(() => expect(() => process.kill(pid, 0)).toThrow(), 5000)
327+
expect((await result).exitCode).toBeUndefined()
328+
expect(result.killed).toBe(true)
329+
}
330+
finally {
331+
if (pid > 0) {
332+
try {
333+
process.kill(pid)
334+
}
335+
catch {}
336+
}
337+
}
338+
})
339+
312340
it('getResult() tracks the new run after restart()', async () => {
313341
const { host } = createTerminalHost()
314342

‎packages/hub/src/node/host-terminals.ts‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,25 +36,44 @@ const TERMINAL_BUFFER_LIMIT = 1000
3636
/** TERM handed to spawned PTYs; also used to reject fallback process labels. */
3737
const PTY_TERM_NAME = 'xterm-256color'
3838

39-
/**
40-
* Kill a `startChildProcess()` run together with everything it spawned.
41-
*
42-
* On Windows, tinyexec runs anything that isn't a `.exe`/`.com` - including
43-
* the `node_modules/.bin/*.cmd` shims package managers generate - through
44-
* `cmd.exe /d /s /c`, so the pid held here is the wrapper's. Killing a process
45-
* on Windows doesn't reach its descendants, so `cp.kill()` alone would leave
46-
* the real program running (and holding its ports). `taskkill /T /F` ends the
47-
* whole tree; `cp.kill()` stays the fallback and the POSIX path.
48-
*/
39+
function processTree(pid: number, psOutput: string): number[] {
40+
const children = new Map<number, number[]>()
41+
for (const [, childPid, parentPid] of psOutput.matchAll(/^\s*(\d+)\s+(\d+)$/gm)) {
42+
const parent = Number(parentPid)
43+
if (!children.has(parent))
44+
children.set(parent, [])
45+
children.get(parent)!.push(Number(childPid))
46+
}
47+
const tree = new Set([pid])
48+
for (const parent of tree) {
49+
for (const child of children.get(parent) ?? [])
50+
tree.add(child)
51+
}
52+
return [...tree]
53+
}
54+
55+
// On Windows, tinyexec runs non-.exe/.com commands such as node_modules/.bin/*.cmd
56+
// through cmd.exe /d /s /c. Killing that shell PID leaves the real program running.
57+
// taskkill stops the whole tree. On POSIX, use ps to stop children before their parents.
4958
async function killProcessTree(cp: TinyExecResult): Promise<void> {
5059
const child = cp.process
5160
const pid = child?.pid
52-
if (process.platform !== 'win32' || !child || pid === undefined || child.exitCode !== null || child.signalCode !== null) {
61+
if (!child || pid === undefined || child.exitCode !== null || child.signalCode !== null) {
5362
cp.kill()
5463
return
5564
}
5665
const { exec } = await import('tinyexec')
5766
try {
67+
if (process.platform !== 'win32') {
68+
const { stdout } = await exec('ps', ['-A', '-o', 'pid=,ppid='], { throwOnError: true })
69+
for (const target of processTree(pid, stdout).reverse()) {
70+
try {
71+
process.kill(target, 'SIGTERM')
72+
}
73+
catch {}
74+
}
75+
return
76+
}
5877
const { exitCode } = await exec('taskkill', [
5978
'/pid',
6079
String(pid),

0 commit comments

Comments
 (0)