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

家长

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,我会看到父进程仍在运行。
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 文档:


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/

10-12 00:26
查看更多