Nikita  Luparev Nikita Luparev - 3 months ago 14x
Node.js Question

Is it possible to find process using pid and send a message to it?

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.


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