私は2つの解決策を見つけましたが、どちらも完璧ではありません。
1. SIGTERM シグナルを受信したら、kill(-pid) ですべての子プロセスを終了します。
明らかに、このソリューションは「kill -9」を処理できませんが、すべての子プロセスを覚えておく必要がないため、ほとんどの場合に機能し、非常に単純です。
var childProc = require('child_process').spawn('tail', ['-f', '/dev/null'], {stdio:'ignore'});
var counter=0;
setInterval(function(){
console.log('c '+(++counter));
},1000);
if (process.platform.slice(0,3) != 'win') {
function killMeAndChildren() {
/*
* On Linux/Unix(Include Mac OS X), kill (-pid) will kill process group, usually
* the process itself and children.
* On Windows, an JOB object has been applied to current process and children,
* so all children will be terminated if current process dies by anyway.
*/
console.log('kill process group');
process.kill(-process.pid, 'SIGKILL');
}
/*
* When you use "kill pid_of_this_process", this callback will be called
*/
process.on('SIGTERM', function(err){
console.log('SIGTERM');
killMeAndChildren();
});
}
同様に、どこかで process.exit を呼び出すと、上記のように「exit」ハンドラーをインストールできます。注: Ctrl+C と突然のクラッシュは、プロセス グループを強制終了するために OS によって自動的に処理されているため、ここでは省略します。
2. chjj /pty.jsを使用して、制御端末が接続されたプロセスを生成します。
とにかく kill -9 で現在のプロセスを強制終了すると、すべての子プロセスも自動的に強制終了されます (OS によって?)。現在のプロセスは端末の別の側を保持しているため、現在のプロセスが終了すると、子プロセスが SIGPIPE を取得して終了すると思います。
var pty = require('pty.js');
//var term =
pty.spawn('any_child_process', [/*any arguments*/], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.cwd(),
env: process.env
});
/*optionally you can install data handler
term.on('data', function(data) {
process.stdout.write(data);
});
term.write(.....);
*/