javascript - Node.js - child_process 和集群混淆

标签 javascript node.js concurrency

举个简单的例子:我有一个名为 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/

相关文章:

asp.net - 如何将 session 值传递给外部js文件

javascript - Rails - 为一个 Controller 生成两个 javascript 文件,因此 js 函数执行两次

node.js - Docker 中运行的 Node.JS 应用程序出现段错误

node.js - 如何在 Node.js 中使 ZeroMQ 发布者变得冗余?

javascript - Node.JS - 处理某些类型的 promise 拒绝?

java - 对象创建(状态初始化)和线程安全

java - 在单独的 JavaFX 线程中排队打印作业

javascript - 创建 CSS/Javascript/jQuery 'like heart'

mongodb - 如何在考虑并发性的情况下更新多行?

javascript - TUI(Toast UI)日历 API 未按预期工作。