@frank-shaw
2016-09-23T02:04:00.000000Z
字数 1130
阅读 3990
node.js
子进程与父进程之间如何通信这个问题,我们可以直接看文档:
http://wiki.jikexueyuan.com/project/nodejs/child-processes.html
使用 child_process.fork() 的时候,你能用 child.send(message, [sendHandle]) 给子进程写数据,子进程通过 'message' 接收消息。
子进程代码里的 process 对象拥有 send() 方法,当它通过信道接收到信息时会触发,并返回对象。
表示的就是:当子进程接受到父进程发送过来的数据的时候,(如果它包含有send()方法)那么它也会立刻返回想要的消息给父进程。
一个简单的例子:
//parent.jsvar cp = require('child_process');var n = cp.fork(__dirname + '/sub.js');n.on('message', function(m) {console.log('Parent got message: ', JSON.stringify(m));});n.send({ hello: 'world' });//sub.jsprocess.on('message', function(m) {console.log('Child got message: ', JSON.stringify(m));});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() 来关闭它。
