这个答案只是为了提供一个 entropo 提出的 node-ffi 解决方案的例子(上面)(如前所述,它将在 linux 上工作):
这是父进程,它正在生成子进程,然后在 5 秒后退出:
var spawn = require('child_process').spawn;
var node = spawn('node', [__dirname + '/child.js']);
setTimeout(function(){process.exit(0)}, 5000);
这是子进程(位于 child.js 中)
var FFI = require('node-ffi');
var current = new FFI.Library(null, {"prctl": ["int32", ["int32", "uint32"]]})
//1: PR_SET_PDEATHSIG, 15: SIGTERM
var returned = current.prctl(1,15);
process.on('SIGTERM',function(){
//do something interesting
process.exit(1);
});
doNotExit = function (){
return true;
};
setInterval(doNotExit, 500);
如果没有 current.prctl(1,15),即使父母快死了,孩子也会永远跑下去。在这里,它将使用 SIGTERM 发出信号,该信号将被优雅地处理。