gpt4 book ai didi

javascript - 为什么父进程在运行一个分离的子进程后不会自动退出?

转载 作者:行者123 更新时间:2023-11-29 20:58:39 25 4
gpt4 key购买 nike

Node.js 8.9.1,Linux 版本 4.10.0-42-generic

parent

const { fork } = require('child_process');

const forked = fork('child.js', {
detached: true,
stdio: 'ignore'
});

const config = {
name: 'trex',
interval: 2000
};

forked.send(config);
forked.unref();

for (let i = 0; i < 3; i++) {
console.log('do staff');
}

child

const work = function() {
let sum = 0;
for (let i = 0; i < 1e10; i++) {
sum += i;
}
};

const start = function(config) {
setTimeout(function run() {
work();
setTimeout(run, config.interval);
}, config.interval);
};

process.on('message', function(config) {
start(config);
});

我需要 parent 启动 child 并正常退出。现在,如果我执行 node parent.js,我会看到父 Node 仍在运行。

trex@beast-cave:~/dev/$ ps aux | grep -e "parent\|child" | grep node
trex 5134 0.0 0.1 874016 29460 pts/11 Sl+ 10:44 0:00 node parent.js
trex 5140 86.3 0.1 874108 30252 ? Rsl 10:44 4:59 /home/trex/.nvm/versions/node/v8.9.1/bin/node child.js

我知道有 process.exit()。但是为什么不能正常退出呢?在我的应用程序中,父级在 setTimeout 循环中,其中有很多逻辑并且必须在一个时间间隔内只运行一次。

最佳答案

来自 https://nodejs.org/api/child_process.html文档:

subprocess.disconnect()# Added in: v0.7.2 Closes the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling this method the subprocess.connected and process.connected properties in both the parent and child (respectively) will be set to false, and it will be no longer possible to pass messages between the processes.

The 'disconnect' event will be emitted when there are no messages in the process of being received. This will most often be triggered immediately after calling subprocess.disconnect().

Note that when the child process is a Node.js instance (e.g. spawned using child_process.fork()), the process.disconnect() method can be invoked within the child process to close the IPC channel as well.

const work = function() {
let sum = 0;
for (let i = 0; i < 1e10; i++) {
sum += i;
}
};

const start = function(config) {
setTimeout(function run() {
work();
setTimeout(run, config.interval);
}, config.interval);
};

process.on('message', function(config) {
start(config);
process.disconnect();
});

关于javascript - 为什么父进程在运行一个分离的子进程后不会自动退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884279/

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