node-pty icon indicating copy to clipboard operation
node-pty copied to clipboard

macOS: spawn-helper waits in open() forever when the spawning process dies before it opens the pty

Open judiazm opened this issue 3 weeks ago • 0 comments

On macOS, if the process that calls pty.spawn() dies within a few milliseconds of the call, spawn-helper never runs the program. It stays in open() forever, with parent pid 1 and no controlling terminal, and nothing will ever signal it. We found such helpers several days old on a developer machine, left by test runs whose worker was killed while starting terminals.

Reproduce

node-pty 1.1.0 (prebuilt darwin-arm64), Node 24.22.1, macOS 27.2 on Apple Silicon.

// repro.mjs: spawn 10 ptys, then die at once, as a killed test worker does
import pty from "node-pty";
for (let i = 0; i < 10; i++) pty.spawn("/bin/sleep", ["60"], { cols: 80, rows: 24 });
process.kill(process.pid, "SIGKILL");
$ node repro.mjs; sleep 1; ps -Ao pid,ppid,stat,args | awk '$2==1 && /spawn-helper/'
40306     1 Ss   …/node_modules/node-pty/prebuilds/darwin-arm64/spawn-helper <cwd> /bin/sleep 60
40307     1 Ss   …/node_modules/node-pty/prebuilds/darwin-arm64/spawn-helper <cwd> /bin/sleep 60
… (10 of 10)

They are still there long after sleep 60 would have ended. sample <pid> shows every one in the same place:

main  (in spawn-helper) + 32
  open  (in libsystem_kernel.dylib) + 64

lsof shows fds 0 to 2 on the pty slave (/dev/ttysNNN), and ps shows no controlling terminal (TTY ??). Exiting after a setTimeout(…, 0) instead of at once leaves about 1 helper in 5, and waiting 5 ms or more leaves none, because by then the helper has opened the slave and become the program, which gets SIGHUP when the master closes.

Cause

src/unix/spawn-helper.cc takes its controlling terminal by reopening the slave:

char *slave_path = ttyname(STDIN_FILENO);
close(open(slave_path, O_RDWR));

As far as we can tell, macOS's pty slave open waits for carrier unless O_NONBLOCK is set, and carrier drops when the master closes. If the parent dies (closing the master) between posix_spawn and this open(), the open never returns. The parent is gone, so nothing calls kill() on the helper's pid.

Possible fix

Untested: take the controlling terminal with ioctl(STDIN_FILENO, TIOCSCTTY, 0) on the slave the helper already has as stdin (it is already a session leader from POSIX_SPAWN_SETSID), or open with O_NONBLOCK. Either way, the helper would fail or exec instead of waiting. A test could run the script above and assert that no helper with parent pid 1 is left a second later.

We work around it by ending orphaned processes whose path is our node-pty's spawn-helper before and after our test runs.

Filed by Claude Opus 5.5 in Claude Code.

judiazm avatar Nov 07 '26 20:11 judiazm