举个简单的例子:我有一个名为 parent.js
的文件,代码如下:
var child_process = require('child_process')
var forker = child_process.fork(__dirname + '/child.js')
forker.on('message', function (msg) {
console.log('PARENT got message:', msg)
})
// sends a message to the forked process?
forker.send({msg: 'Parent message.'})
第一个问题:我说对了吗? child_process.fork()
返回 forker 进程,不是吗? (如 child_process.spawn()
?)
无论如何,这是 child.js
的代码:
process.on('message', function (msg) {
console.log('CHILD got message:', msg)
})
// sends a message to the forker process? why?
process.send({msg: 'Message from the child.'})
第二个问题:process
在子进程内部指的是什么?我猜对当前的 fork 进程?如果是这样,当我调用 process.send()
时,我正在向父进程发送消息,对吗?
第三个问题:举这个例子(Node: Up and Running 的简化版):
var cluster = require('cluster')
if (cluster.isMaster) {
// fork child...
var worker = cluster.fork()
worker.on('message', function (msg) {
// do stuff
})
} else if (cluster.isWorker) {
process.send(aMessage)
}
我发现不清楚的是:worker
是上一个示例的 forker
的一种吗?而worker内部的process.send()
向forker进程发送消息?
最佳答案
1) child_process.fork()
返回派生进程的方式与 child_process.spawn()
返回新生成的进程相同。确实,fork()
只是
[...] a special case of the
spawn()
functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in.1
2)子中的process
指的是子process
。还有,
In the child the process object will have a send() method, and process will emit objects each time it receives a message on its channel.2
因此,我们可以从 child 内部使用'send()' 发送消息,我们可以使用.on('message')
接收它们。就像在您的代码段中一样。
3) 如关于 Node.js 上的 cluster
模块的文档所述:
The worker processes are spawned using the
child_process.fork method
, so that they can communicate with the parent via IPC and pass server handles back and forth. 3
所以你是对的。 Node集群以更实用的方式封装了process
的功能(请注意此时cluster
模块被标记为experimental。Api可能会在不久的将来)。
关于javascript - Node.js - child_process 和集群混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417552/