我正在尝试在 node.js 中创建一个程序,使用以下命令创建两个进程fork()
的方法childproccess
。流程如下:
我想直接在两个子进程之间传输数据,而不是在父进程和子进程之间传输数据。我向您展示了我正在尝试做的事情的图表。
子进程之间的通信
我尝试使用以下代码,但它对我不起作用。
In the 父亲.js代码中,我创建子进程如下:
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的代码:
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");
});
我如何发送和接收消息son1.js
to son2.js
反之亦然,无需发送消息至father.js
?