防止信号传播到子进程(NodeJS)

时间:2017-01-21 01:38:15

标签: node.js stdin spawn

我有以下NodeJS代码:

[myFile.js]

var path  = require("path");
var cp  = require("child_process");
var child = cp.spawn( "python",["HelloWorld.py"], { stdio:'pipe', });

child.stdout.on('data', (data) => {
    console.log(`CHILD stdout: ${data }`);
});

child.stderr.on('data', (data) => {
  console.log(`CHILD stderr: ${data}`);
});

process.on("SIGINT",()=>{
    // close gracefully
    console.log("Received SIGINT");
})
child.on('exit',(code)=>{console.log(`child Process exited with code ${code}`)})

和python脚本如:

[HelloWorld.py]

print 'Hi there'
import time
time.sleep(5)

我想优雅地管理关机,但是当我通过命令行启动此代码时:

> node myFile.js

并按下control-C,我将其打印到控制台:

^CReceived SIGINT
CHILD stdout: Hi there

CHILD stderr: Traceback (most recent call last):
  File "HelloWorld.py", line 3, in <module>
    time.sleep(5)
KeyboardInterrupt

child Process exited with code 1

表示python(在子进程中运行)收到了&#39; ^ C&#39;键盘事件。但是,我更喜欢更优雅地退出子进程,而不是崩溃键盘中断。

我尝试了options.stdio的各种组合,包括[undefined,'pipe','pipe'](没有工作)和['ignore','pipe','pipe'](导致子进程崩溃),以及我试过worker.stdin.end()(这也导致子进程崩溃)。

有没有办法从父NodeJS进程继承标准?

1 个答案:

答案 0 :(得分:-1)

RTFM:将options.detached设置为true是阻止传播kill信号的原因,其中(惊讶)就是当父级被杀时,子进程被杀死的方式......