14

Take this brief example: I have a file called parent.js, with the following code:

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.'})

First question: am I getting this right? child_process.fork() returns the forker process, doesn't it? (like child_process.spawn()?)

Anyway, here's the code for 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.'})

Second question: what does process refer to inside the child process? To the current forked process I guess? If so, when I call process.send() I'm sending a message to the parent process right?

Third question: take this example (simplified version from 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)
}

What I find unclear is: worker is kind of the forker of the previous example? And process.send() inside the worker sends a message to the forker process?

4

1 回答 1

14

1)以与返回新生成的进程child_process.fork()相同的方式返回分叉的进程。child_process.spawn()的确,fork()只是

spawn()[...] 生成节点进程的功能的一个特例。除了在普通 ChildProcess 实例中包含所有方法外,返回的对象还内置了一个通信通道。1

2)process中child 指child process。还,

在子进程中,进程对象将有一个 send() 方法,并且进程每次在其通道上接收到消息时都会发出对象。2

因此,我们可以从孩子内部使用“send()”发送消息,然后我们可以使用 接收它们.on('message')。就像在你的片段中一样。

3) 如cluster关于 Node.js 上的模块的文档中所述:

工作进程是使用 生成的child_process.fork method,因此它们可以通过 IPC 与父进程通信并来回传递服务器句柄。3

所以你是对的。节点集群以更可用的方式包装了功能process(请注意,此时cluster模块被标记为实验性的。Api 可能会在不久的将来发生变化)。

于 2013-08-24T11:39:15.327 回答