[英]Nodejs child process exit behavior
我有一些奇怪的(对我来说)行为,我不明白。 请帮忙。
这里有一个父进程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] });
这里有一个孩子(使用 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();
});
如果我运行父代码,我会从孩子那里得到正确的消息,而孩子会等待另一条消息。
所以我不明白的一点是,为什么子进程在运行后没有立即退出并等待来自父进程的消息。 因为如果我只运行子代码: node test-child.js
,它会立即退出。
谢谢大家的回答。
请再解释一件事。 如果我换成孩子
process.on('message', ...)
到process.once('message', ...)
然后得到孩子的回应,然后Exited with code: 0
为什么? 我没有明确杀死子进程......
所以我决定回答自己,因为其他答案并没有完全阐明情况。
只是测试了一些代码,发现了一些有趣的东西。 例如,如果我们有一些代码的子进程:
process.send({message: 'foo'})
或简单console.log('foo')
它只是立即退出。
但是有一些进程事件,如果你有监听回调,它会阻止子进程退出。 例如process.on('message', ...)
或process.on('disconnect', ...)
。
现在process.once('message', ...)
的情况很清楚了。 它只是在触发一次后删除侦听器。 所以现在,没有监听器,没有什么能阻止子进程退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.