Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my forked child process exit immediately after I fork it?

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?

like image 242
Joey Avatar asked Oct 15 '25 11:10

Joey


1 Answers

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');
});
like image 184
chris Avatar answered Oct 18 '25 02:10

chris