[关闭]
@frank-shaw 2016-09-23T02:04:00.000000Z 字数 1130 阅读 2597

child_process中子进程与父进程之间的通信与断开连接

node.js


如何通信

子进程与父进程之间如何通信这个问题,我们可以直接看文档:
http://wiki.jikexueyuan.com/project/nodejs/child-processes.html

使用 child_process.fork() 的时候,你能用 child.send(message, [sendHandle]) 给子进程写数据,子进程通过 'message' 接收消息。

子进程代码里的 process 对象拥有 send() 方法,当它通过信道接收到信息时会触发,并返回对象。

表示的就是:当子进程接受到父进程发送过来的数据的时候,(如果它包含有send()方法)那么它也会立刻返回想要的消息给父进程。

一个简单的例子:

  1. //parent.js
  2. var cp = require('child_process');
  3. var n = cp.fork(__dirname + '/sub.js');
  4. n.on('message', function(m) {
  5. console.log('Parent got message: ', JSON.stringify(m));
  6. });
  7. n.send({ hello: 'world' });
  8. //sub.js
  9. process.on('message', function(m) {
  10. console.log('Child got message: ', JSON.stringify(m));
  11. });
  12. process.send({ foo: 'bar' });

通过控制台运行指令node parent.js我们可以看到结果:

Parent got message: {"foo" : "bar"}
Child got message: {"hello": "world"}

如何断开连接

child.disconnect()

关闭父子进程间的所有 IPC 通道,能让子进程优雅的退出。调用这个方法后,父子进程里的.connected 标志会变为 false,之后不能再发送消息。

当进程里没有消息需要处理的时候,会触发 'disconnect' 事件。

注意,在子进程还有 IPC 通道的情况下(如 fork() ),也可以调用 process.disconnect() 来关闭它。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注