我不确定这里发生了什么,但是当我使用 fork 启动以下进程时,我的主进程输出 Child process "+ cid + "running
,但是当我尝试发送一个给 child 的消息 "Child process "+ data
不输出。我也不知道为什么。
这是子进程:
var running = true;
var cid = process.env.cid;
process.on("message", function(data){
data = (data + "").trim().toLowerCase();
process.send("Child process " + data);
});
process.send({cid: cid, msg: "Child process " + cid + " running"});
while(running){
}
process.send("Child stopped!");
我是这样开始 child 的:
var children = [];
for(var i = 0; i < 5; i++){
children[i] = cp.fork("./child.js", [], {
// silent: true,
cwd: __dirname,
env: {
cid: i
}
});
children[i].on("message", function(msg){
console.log("Message from " + msg.cid + ": " + msg.msg);
});
}
然后我发送这样的消息:
for(var i in children){
console.log(" Sending message to child " + i);
children[i].send("msg");
}
当我运行 server.js
时,我得到了这个输出:
Message from 1: Child process 1 running
Message from 0: Child process 0 running
Message from 2: Child process 2 running
Message from 3: Child process 3 running
Message from 4: Child process 4 running
Sending message to child 0
Sending message to child 1
Sending message to child 2
Sending message to child 3
Sending message to child 4
但他们似乎没有任何回应。
我没有收到任何错误,子进程也没有输出。发生这种情况的原因是什么?
最佳答案
您可以删除无限 while 循环,当有事件的事件监听器时, child 不应该退出,除非您显式调用 process.exit()
在退出时使用事件样式,而不是以程序样式告诉子进程在最后一行结束:
process.on('exit', function(code) {
process.send("Child stopped!");
});
由于事件仅在进程空闲时处理,因为 javascript 不实现线程。因此,while
循环将阻塞进程,阻止它接收消息。
关于javascript - 子进程收不到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29504609/