On May 25, 2014, at 1:00 AM, Liu Wei wrote:
> Thanks ryandesign. this child_process is just for handling download csv files and then zip them. So the master process will do display csv files data and CRUD with Nosql.
Is that in your code now? It wasn't in the code you showed us. Again, if there is nothing else for a node app to do, it will quit. If all the master is doing is waiting for a child process to exit, then when the child process exits, the master will also exit.
Additionally, your code requests that the master process exit whenever the child process exits. It says so right here:
fork.onUnexpectedExit = function (code, signal) {
process.exit(1);
};
fork.on("exit", fork.onUnexpectedExit);
You invent a new property on the child object called "onUnexpectedExit" and declare it as a function that exits the master when called. Then you ask node to call that function when the child emits the "exit" event. The "exit" event is emitted when the child exits, regardless of its code, so the property name "onUnexpectedExit" that you've chosen is misleading; the only reference I found to a property of that name is in this blog, so I guess you copied it from there:
https://www.exratione.com/2013/05/die-child-process-die/
If you only want to exit on unusual conditions, you should first check that the code argument is nonzero.
Here is a revised version that shows that the master stays running if you give it something else to do (like print a message once a second):
/* master.js */
var cp = require('child_process'),
fork = cp.fork('./child.js');
fork.send({ zip: '111' });
fork.on('message', function (msg) {
if (msg.status === 'done') {
fork.kill('SIGTERM');
}
});
fork.on('exit', function (code, signal) {
if (code) {
console.log('child exited unexpectedly with code', code);
process.exit(1);
} else {
console.log('child exited normally');
}
});
// Simulate other work happening in the master.
var i = 0;
setInterval(function () {
console.log(++i % 2 ? 'tick' : 'tock');
}, 1000);
/* child.js */
process.on('message', function (m) {
if (m.zip === '111' ) {
//Do something logic
//Simulate task taking 2.5 seconds to complete
setTimeout(function () {
process.send({status: 'done'});
}, 2500);
}
});
process.on('uncaughtException', function (err) {
console.log("child.js: " + err.message + "\n" + err.stack + "\n Stopping background timer");