gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:01 26 4
gpt4 key购买 nike

我的 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(在子进程中运行)收到了'^C'键盘事件。但是,我更愿意更优雅地退出子进程,而不是因键盘中断而崩溃。

我尝试了各种组合 options.stdio ,包括 [undefined,'pipe','pipe'] (这不起作用)和 ['ignore','pipe','pipe'] (这导致了子进程崩溃),我尝试了 worker.stdin.end() (这也导致了子进程崩溃)。

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

最佳答案

RTFM:设置options.detached to true 是阻止传播终止信号的原因,这(令人惊讶)是当父进程被终止时附加的子进程如何被终止的......

关于node.js - 防止信号传播到子进程 (NodeJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41774895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com