正如您所拥有的那样,您的代码永远不会收到超过一条消息,因为它会立即进入无限循环,永远不会将控制权返回给事件循环。该message
变量永远不会神奇地改变,并且由于节点是单线程的,因此除非第一条消息评估为假,否则子节点无法退出。
我认为你想要更像这样的东西:
var i = 0;
process.on("message", function(message)
{
if(message)
{
console.log("CP aCapLive received message: Iteration " + i++);
}
else
{
console.log("CP aCapLive is going to exit now...");
process.exit();
}
});
如果你想要一个无限循环,你必须在每次迭代后将控制权返回给事件循环。这将允许新消息进入。示例:
var _message;
var _running = false;
process.on("message", function (message)
{
_message = message; // update the _message var when a new one comes in
if (!_running) // this just prevents multiple loops from being started.
{
_running = true;
run();
}
});
var i = 0;
function run ()
{
if(_message)
{
console.log("CP aCapLive received message: Iteration " + i++);
setImmediate(run); // <-- this causes an infinite non-blocking loop
}
else
{
console.log("CP aCapLive is going to exit now...");
process.exit();
}
}
如果message
每次都一样,那么您真正想要的是这样的切换系统:
var _message = false;
process.on("message", function ()
{
_message = !_message; // update the _message var when a new one comes in
if (_message)
run();
});
var i = 0;
function run ()
{
if(_message)
{
i++;
if (i % 10000 === 0)
console.log("CP aCapLive received message: Iteration " + i);
setImmediate(run); // <-- this causes an infinite non-blocking loop
}
else
{
console.log("CP aCapLive is going to exit now...");
process.exit();
}
}
这是我用来测试它的父进程代码:
var childProcess = require('child_process');
var proc = childProcess.fork('child.js');
proc.send(true);
setTimeout(function () { proc.send(true); }, 4000); // send second message
输出:
CP aCapLive received message: Iteration 10000
CP aCapLive received message: Iteration 20000
CP aCapLive received message: Iteration 30000
... full output omitted for brevity ...
CP aCapLive received message: Iteration 1660000
CP aCapLive received message: Iteration 1670000
CP aCapLive received message: Iteration 1680000
CP aCapLive is going to exit now...