Node.js 中子进程之间的通信

Est*_*cio 5 parallel-processing fork communication child-process node.js

我正在尝试在 node.js 中创建一个程序,使用 的fork()方法创建两个进程childproccess。流程如下:

  • 父亲.js
  • Son1.js
  • Son2.js

我想直接在两个子进程之间传输数据,而不是在父进程和子进程之间传输数据。我向您展示了我正在尝试做的事情的图表。

子进程之间的通信

我尝试使用以下代码,但它对我不起作用。

father.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});
Run Code Online (Sandbox Code Playgroud)

Son1.js代码:

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"); 
});
Run Code Online (Sandbox Code Playgroud)

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");         
});
Run Code Online (Sandbox Code Playgroud)

如何在不向 发送消息的情况下从son1.js向发送消息son2.js并从 向 接收消息,反之亦然father.js

msc*_*dex 1

您必须打开另一个通信通道,例如本地套接字(tcp、udp 或 unix)或第三方服务(例如 redis)。