SuperManEver
SuperManEver

Reputation: 2362

How to send a message to a child process created using fork()?

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.

Upvotes: 4

Views: 2097

Answers (1)

Fabio Antunes
Fabio Antunes

Reputation: 22862

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' });

Upvotes: 3

Related Questions