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

Node.js 防止信号传播到子进程(NodeJS),node.js,stdin,spawn,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 }`); });

我有如下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
^CReceived SIGINT
孩子:你好
子stderr:回溯(最近一次呼叫最后一次):
文件“HelloWorld.py”,第3行,在
时间。睡眠(5)
键盘中断
子进程已退出,代码为1
指示python(在子进程中运行)收到“^C”键盘事件。然而,我更愿意优雅地退出子进程,而不是在键盘中断时崩溃

我尝试了多种组合,包括
[未定义,'pipe','pipe']
(不起作用)和
['ignore','pipe','pipe']
(导致子进程崩溃),我还尝试了
worker.stdin.end()
(也导致子进程崩溃)


有没有办法不从父节点JS进程继承标准

RTFM:设置为
true
是防止传播终止信号的原因,这(令人惊讶)是当父进程终止时附加的子进程是如何终止的…

您反对在python脚本中捕获异常吗?如果没有,可以将其包装在
try
catch
语句中以消除错误。请看:这一点很好,但我的问题是关于NodeJS的,而不是关于Python的。我在上面的示例中使用python是因为(A)它清楚地表明键盘中断正在传递给子进程,并且(B)我正在编写的代码是为通用任务运行程序编写的,而且不可能在子进程中运行的每个脚本和语言中都注入try/catch——最好首先防止中断被发送到子进程。(如果你因为snark而否决投票,请意识到我在回答我自己的问题…)我承认我投了反对票。我不知道你回答了自己,对此我很抱歉。我可以删除否决票,但您已经编辑了您的答案。同样值得一提的是,终端中的
^C
SIGINT
发送到整个流程组。如果手动
kill
主进程,则应该能够优雅地停止子进程,而无需分离它们。systemd.service也会发生类似的情况,但您可以在这里设置
KillMode