-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9ad3d3c
commit 5a52f0d
Showing
2 changed files
with
66 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
const psTree = require('ps-tree'); | ||
const { exec } = require('child_process'); | ||
|
||
const unixKillCommand = 'kill -9'; | ||
const windowsKillCommand = 'taskkill /F /PID'; | ||
|
||
function killProcessAndChildren(pid, isWindows = false) { | ||
return new Promise((resolve, reject) => { | ||
psTree(pid, (err, children) => { | ||
if (err) { | ||
reject(err); | ||
return; | ||
} | ||
|
||
// Array of PIDs to kill, starting with the children | ||
const pidsToKill = children.map((p) => p.PID); | ||
pidsToKill.push(pid); // Also kill the main process | ||
|
||
const killCommand = isWindows ? windowsKillCommand : unixKillCommand; | ||
const joinedCommand = pidsToKill | ||
.map((pid) => `${killCommand} ${pid}`) | ||
.join('; '); // Separate commands with a semicolon, so they run in sequence even if one fails. Also works on Windows. | ||
|
||
exec(joinedCommand, (err) => { | ||
if (err?.message?.includes('No such process')) { | ||
return; // Ignore errors for processes that are already dead | ||
} | ||
reject(err); | ||
}); | ||
|
||
resolve(); | ||
}); | ||
}); | ||
} | ||
|
||
module.exports = { killProcessAndChildren }; |