I'm trying to make a program in node.js that creates two processes using the fork() method of childproccess. The processes are as follows:
- Father.js
- Son1.js
- Son2.js
I want to transfer data between two child processes directly, not between father and children. I show you a graph of what I'm trying to do.
communication between child proccess
I tried with the following code, but it did not work for me.
In the father.js code, I 'm creating the childs processes as follows:
const cp = require("child_process");
var son1 = cp.fork("${__dirname}/son1.js");
var son2 = cp.fork("${__dirname}/son2.js");
console.log("father sending message to son1..");
son1.send({msg:'Hi son1',br:son2});
console.log("father sending message to son2..");
son2.send({msg:'Hi son1',br:son1});
The Son1.js's code:
var brother=null;
process.on('message', function(json)
{
console.log('message father in son1.js;', json.msg);
brother=json.br;
brother.send("hello I'm son1.js");
});
And the Son2.js 's code:
var brother=null;
process.on('message', function(json)
{
console.log('message father in son2.js;', json.msg);
brother=json.br;
brother.send("hello I'm son2.js");
});
How can I send and receive messages from son1.js to son2.js and vice versa without sending messages to father.js?