-
Notifications
You must be signed in to change notification settings - Fork 39
Description
When using tree-kill on macOS within applications that frequently restart (such as NestJS in watch mode), the module fails with a spawn EBADF error. The error occurs in the buildProcessTree function when attempting to spawn child processes to get the process tree. This appears to be due to file descriptor handling issues specific to macOS.
Environment
OS: macOS 15.3.1
Node.js version: v20.18.3
tree-kill version: v1.2.2
Error stack trace
node:internal/child_process:420
throw new ErrnoException(err, 'spawn');
^
Error: spawn EBADF
at ChildProcess.spawn (node:internal/child_process:420:11)
at spawn (node:child_process:762:9)
at /Users/.../node_modules/tree-kill/index.js:33:18
at buildProcessTree (/Users/.../node_modules/tree-kill/index.js:90:14)
at module.exports (/Users/.../node_modules/tree-kill/index.js:32:9)
at /Users/.../node_modules/@nestjs/cli/actions/start.action.js:57:17
at Object.onWatchStatusChange (/Users/.../node_modules/@nestjs/cli/lib/compiler/watch-compiler.js:83:17)
at /Users/.../node_modules/typescript/lib/typescript.js:124995:32
at emitFilesAndReportErrors (/Users/.../node_modules/typescript/lib/typescript.js:124843:7)
at result.afterProgramCreate (/Users/.../node_modules/typescript/lib/typescript.js:124991:7) {
errno: -9,
code: 'EBADF',
syscall: 'spawn'
}
Noticed this started happening after updating macOS to Sequoia(v15).
The issue appears to be related to how spawn handles file descriptors on macOS when used recursively in rapid succession. The current implementation uses spawn to build the process tree, which can lead to file descriptor exhaustion or race conditions when processes are frequently being killed and restarted. I'm using nestjs cli in a monorepo, so can be because of the large number of files.
I have tested a fix that uses execSync, happy to submit a PR if this looks good:
function buildProcessTreeMacOS(parentPid, tree, pidsToProcess, cb) {
try {
let stdout = '';
try {
stdout = execSync('pgrep -P ' + parentPid, {
encoding: 'utf8',
timeout: 2000,
maxBuffer: 1024 * 1024
});
} catch (execError) {
if (execError.status !== 1) {
throw execError;
}
}
delete pidsToProcess[parentPid];
const childPids = stdout.trim().split('\n').filter(Boolean);
if (childPids.length === 0) {
if (Object.keys(pidsToProcess).length === 0) {
cb();
}
return;
}
childPids.forEach(function(pidStr) {
const pid = parseInt(pidStr, 10);
if (!isNaN(pid)) {
tree[parentPid].push(pid);
tree[pid] = [];
pidsToProcess[pid] = 1;
buildProcessTreeMacOS(pid, tree, pidsToProcess, cb);
}
});
} catch (err) {
delete pidsToProcess[parentPid];
if (Object.keys(pidsToProcess).length === 0) {
cb();
}
}
}