I need to fork/spawn processes from my main node application. This processes should run "endless" as they check filesystem for changes in different folders and process new files.
I fork processes in the following way:
var processes = [];
var fork = require('child_process').fork;
var processList = [
{'servicename':'faxservice1'},
{'servicename':'faxservice2'},
{'servicename':'faxservice3'}
];
timeOutValue = 10000;
processList.forEach(Service => {
var cp = fork(['./modules/services/inbound/fax/service.js']);
cp.on('close', function() {
console.log('child process has ended');
process.exit();
})
cp.on('message', (m) => {
console.log(`SVC | ${m}`);
});
setTimeout(function() {
cp.send('stop');
}, timeOutValue);
// Push spawned process to process-array
processes.push(cp);
timeOutValue = timeOutValue + 5000;
});
The child processes do the following:
const svcName = 'FAX-INBOUND';
var chokidar = require('chokidar');
var watcher = chokidar.watch('file, dir, or glob', {
ignored: /[\/\\]\./, persistent: true
});
var log = console.log.bind(console);
var args = process.argv.slice(2);
console.log(`${svcName} | ${args} | starting`);
process.on('message', (m) => {
console.log(`${svcName} | ${m} | Service termination command recieved from host`);
process.exit();
});
watcher
.on('add', function(path) { log(svcName + " | " + 'File', path, 'has been added'); })
.on('addDir', function(path) { log(svcName + " | " + 'Directory', path, 'has been added'); })
.on('change', function(path) { log(svcName + " | " + 'File', path, 'has been changed'); })
.on('unlink', function(path) { log(svcName + " | " + 'File', path, 'has been removed'); })
.on('unlinkDir', function(path) { log(svcName + " | " + 'Directory', path, 'has been removed'); })
.on('error', function(error) { log(svcName + " | " + 'Error happened', error); })
.on('ready', function() { log(svcName + " | " + 'Initial scan complete. Ready for changes.'); })
.on('raw', function(event, path, details) { log(svcName + " | " + 'Raw event info:', event, path, details); })
If i run the shown code, i see at the log that three processes where forked:
FAX-INBOUND | | starting
FAX-INBOUND | | starting
FAX-INBOUND | Initial scan complete. Ready for changes.
FAX-INBOUND | Initial scan complete. Ready for changes.
FAX-INBOUND | | starting
FAX-INBOUND | Initial scan complete. Ready for changes.
the setTimeout is only for debugging purposes and should send a message to the three forked processes each by each with a 5 Second delay. After the spawned processes revieve the message, they should exit.
BUT At the console i only see the console output of one forked process:
FAX-INBOUND | stop | Service termination command recieved from host
It seems, that if one forked process calls
process.exit()
all forked processes get killed ?
What am i doing wrong?
Regards
In "cp.on('close', ...)" you exit the parent process as soon as a child died. This in turn will kill all forked processes, since they haven't forked with option.detached=true