我想通过SIGINT信号处理优雅地结束子进程。 我有一个启动子进程的主要过程:
const childProcess = require('child_process');
console.log('started main');
const subprocess = childProcess.exec('node childProcess.js', (error, stdout) => {
console.log('error:', error);
console.log('log from child process: .............');
console.log(stdout);
console.log('log from child process - end: .............');
});
console.log('last line main');
subprocess.kill('SIGINT');
setTimeout(() => {
console.log('ended main');
}, 3000);
子进程如下:
const fs = require('fs');
console.log('child started');
process.on('SIGINT', () => {
console.log('child ending');
fs.writeFileSync('test1.txt', 'abc');
process.exit();
});
fs.writeFileSync('test0.txt', 'abc');
setTimeout(() => {
console.log('timeout ended');
}, 2000);
当我从终端用node index.js
启动主进程时,得到以下输出:
started main
last line main
error: { Error: Command failed: node childProcess.js
at ChildProcess.exithandler (child_process.js:272:12)
at ChildProcess.emit (events.js:127:13)
at maybeClose (internal/child_process.js:933:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
killed: true,
code: null,
signal: 'SIGINT',
cmd: 'node childProcess.js' }
log from child process: .............
child started
timeout ended
log from child process - end: .............
ended main
意味着子进程中的SIGINT处理程序未触发。此外,还会创建text0.txt作为副作用,但不会创建text1.txt。我也尝试了在子进程中没有setTimeout的情况,但是SIGINT不会触发。为什么SIGINT不触发?
环境:
ubuntu 16.04
节点v9.6.1
我设法通过在“系统监视器”进程列表中结束子进程来触发SIGTERM。