简体   繁体   English

Nodejs子进程退出行为

[英]Nodejs child process exit behavior

I have some strange (for me) behavior, that i do not understand.我有一些奇怪的(对我来说)行为,我不明白。 Please help.请帮忙。

Here a parent process test-parent.js :这里有一个父进程test-parent.js

const cp = require('child_process');
const path = require('path');

const fork = cp.fork(path.join(__dirname, 'test-child.js'));

fork.on('message', console.log);
fork.on('exit', (code) => {
  console.log('Exited with code:', code);
});

fork.send({ sum: 0, set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, - 1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11] });

and here a child (using a cpu-bound subset sum algorhythm) test-child.js :这里有一个孩子(使用 cpu-bound 子集总和算法) test-child.js

const subsetSumFactory = require('./subset-sum');

process.on('message', (message) => {
  const subsetSum = subsetSumFactory(message.sum, message.set);

  subsetSum.on('match', (subset) => { });

  subsetSum.on('end', (totalSubsets) => {
    process.send({ event: 'end', data: { totalSubsets, pid: process.pid } });
  });

  subsetSum.start();
});

If i run parent code i got right message from child and child waits for another message.如果我运行父代码,我会从孩子那里得到正确的消息,而孩子会等待另一条消息。

So the point that i do not understand, is why child process does not exits immediately after run and waits for message from parent.所以我不明白的一点是,为什么子进程在运行后没有立即退出并等待来自父进程的消息。 Because if i run just child code: node test-child.js , it exits immediately.因为如果我只运行子代码: node test-child.js ,它会立即退出。

UPDATE更新

Thanks all for answers.谢谢大家的回答。

Please explain one more thing.请再解释一件事。 If i replace in child如果我换成孩子

process.on('message', ...) to process.once('message', ...) process.on('message', ...)process.once('message', ...)

then got response from child and then got Exited with code: 0然后得到孩子的回应,然后Exited with code: 0

Why?为什么? I do not explicitly kill the child process...我没有明确杀死子进程......

So i decide to answer myself, because other answers did not fully clarify the situation.所以我决定回答自己,因为其他答案并没有完全阐明情况。

Just testing some code and found out some interesting things.只是测试了一些代码,发现了一些有趣的东西。 For example, if we have child process with some code:例如,如果我们有一些代码的子进程:

process.send({message: 'foo'}) or simply console.log('foo') process.send({message: 'foo'})或简单console.log('foo')

It just exits immediately.它只是立即退出。

But there are some process events, on which if you have listener callback, it prevents child process from exit.但是有一些进程事件,如果你有监听回调,它会阻止子进程退出。 For example process.on('message', ...) or process.on('disconnect', ...) .例如process.on('message', ...)process.on('disconnect', ...)

And now the situation with process.once('message', ...) is clear.现在process.once('message', ...)的情况很清楚了。 It just removes listener after it fired once.它只是在触发一次后删除侦听器。 So now, without listener, nothing stops child process from exit.所以现在,没有监听器,没有什么能阻止子进程退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM