Your code, as you have it, will never receive more than one message because it immediately goes into an infinite loop which never returns control to the event loop. The message
variable is never going to magically change, and, since node is single-threaded, there is no possible way for the child to exit unless the very first message evaluated to false.
I think you're wanting something more like this:
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();
}
});
If you want an infinite loop, you have to return control to the event loop after every iteration. This will allow a chance for new messages to come in. Example:
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();
}
}
If message
is going to be the same every time, what you actually want is a toggle system as such:
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();
}
}
Here's the parent process code I used to test it:
var childProcess = require('child_process');
var proc = childProcess.fork('child.js');
proc.send(true);
setTimeout(function () { proc.send(true); }, 4000); // send second message
Output:
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...