Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use tree-kill on exit to kill process trees spawned by children #12

Merged
merged 8 commits into from
Jun 28, 2019
12 changes: 9 additions & 3 deletions lib/Spawn.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var spawn = require('child_process').spawn;
var childProcess = require('child_process');
var path = require('path');

function Spawn(stream, command, args, name, output) {
var exited = false;
Expand All @@ -13,7 +14,7 @@ function Spawn(stream, command, args, name, output) {
};
}

spawnedProcess = spawn(command, args, options);
spawnedProcess = childProcess.spawn(command, args, options);

this.id = name;

Expand Down Expand Up @@ -52,7 +53,12 @@ function Spawn(stream, command, args, name, output) {

process.on('exit', function(code) {
if (exited === false) {
spawnedProcess.kill();
// 'exit' callback cannot perform asynchronous work
// therefore run standalone-treekill in a subprocess using spawnSync.
// assuming standalone-treekill.js in same directory as Spawn.js
var treeKillScriptPath = path.resolve(__dirname, 'standalone-treekill.js');
var spawnOptions = { stdio: 'inherit' };
childProcess.spawnSync(process.execPath, [treeKillScriptPath, spawnedProcess.pid], spawnOptions);
}
});

Expand Down
9 changes: 9 additions & 0 deletions lib/standalone-treekill.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
var treeKill = require('tree-kill');

var processID = parseInt(process.argv[2]);

treeKill(processID, function(err) {
if (err) {
console.error(err.stack || err);
}
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"keypress": "0.2.1",
"protogram": "1.1.3",
"protogram-help": "1.0.2",
"tree-kill": "1.2.1",
"unparse-args": "1.0.1"
},
"devDependencies": {
Expand Down