儿童过程
当人们想要使用不同的初始化和关注点独立运行进程时,子进程是一种可行的方法。就像群集中的叉子一样,child_process
在其线程中运行,但与叉子不同,它有一种与其父节点通信的方式。
通信是双向的,因此父母和孩子可以收听消息并发送消息。
家长 (../ parent.js)
var child_process = require('child_process');
console.log('[Parent]', 'initalize');
var child1 = child_process.fork(__dirname + '/child');
child1.on('message', function(msg) {
console.log('[Parent]', 'Answer from child: ', msg);
});
// one can send as many messages as one want
child1.send('Hello'); // Hello to you too :)
child1.send('Hello'); // Hello to you too :)
// one can also have multiple children
var child2 = child_process.fork(__dirname + '/child');
孩子 (../child.js)
// here would one initialize this child
// this will be executed only once
console.log('[Child]', 'initalize');
// here one listens for new tasks from the parent
process.on('message', function(messageFromParent) {
//do some intense work here
console.log('[Child]', 'Child doing some intense work');
if(messageFromParent == 'Hello') process.send('Hello to you too :)');
else process.send('what?');
})
消息旁边可以收听许多事件, 如错误,已连接或断开连接。
启动子进程具有与之相关的特定成本。人们希望尽可能少地产卵。