I'm just trying to fork a simple child process and have the IPC channel stay open but it keeps exiting immediately for some reason.
In parent.js:
var child = require('child_process').fork('./child.js');
child.on('hi', function() {
console.log("Hi");
});
child.on('exit', function() {
console.log("Exited");
});
child.send('hello');
In child.js:
process.on('hello', function() {
process.send('hi');
});
I get "Exited" printed to the console immediately, and never get a 'Hi'. Then if I continue to try to send to the child process I get a channel closed error.
Something I am doing wrong?
You need to keep both processes open as a child will close immediately and so will the parent. You can do so with something like this:
parent.js
var child = require('child_process').fork('./child.js');
child.on('message', function () {
console.log("Hi");
});
child.on('exit', function () {
console.log("Exited");
});
setTimeout(() => {
child.send('hello');
}, 1000);
process.stdin.resume();
child.js
process.on('message', function () {
console.log("sending hi");
process.send('hi');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With