4

I have a parent process and it forks some number of child processes. I'm looking for some way how child processes can communicate to parent process using messages. I try to send pid of parent to child process and it would be great if I can send message back using parent's pid.

Thanks in advance.

ZackDeRose
  • 2,146
  • 1
  • 16
  • 28
SuperManEver
  • 2,263
  • 6
  • 28
  • 36
  • just in case someone is using IPC and JSON serialization, what I observed is that it sends message from Child-to-Parent but not Parent-to-Child using `send()` function. When I used `fork` instead of `spawn`, it started sending messages in both ways. – Ankur Thakur Apr 27 '23 at 14:08

1 Answers1

3

If you are using child_process.fork() then when you create a new fork a Child Process is returned.

And according to the documentation:

The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child. See child.send() for details.

It is important to keep in mind that spawned Node.js child processes are independent of the parent with exception of the IPC communication channel that is established between the two. Each process has it's own memory, with their own V8 instances. Because of the additional resource allocations required, spawning a large number of child Node.js processes is not recommended.

And here's the documention for child.send

Where you can find this piece of code:

For example, in the parent script:

const cp = require('child_process');
const n = cp.fork(`${__dirname}/sub.js`);

n.on('message', (m) => {
  console.log('PARENT got message:', m);
});

n.send({ hello: 'world' });

And then the child script, 'sub.js' might look like this:

process.on('message', (m) => {
  console.log('CHILD got message:', m);
});

process.send({ foo: 'bar' });
Fabio Antunes
  • 22,251
  • 15
  • 81
  • 96
  • if I fork more that 1 child process and I'm going to communicate with them, should I consider to use `cluster` module ? – SuperManEver Jul 04 '16 at 13:37
  • 1
    @NikitaLuparev this answer might help make your decision http://stackoverflow.com/questions/13367607/what-are-the-effective-differences-between-child-process-fork-and-cluster-fork – Fabio Antunes Jul 04 '16 at 14:23