我如何产生独立的孩子,并重新build立node.js通信?
首先是代码:
test.js:
var cluster = require("cluster"); if (cluster.isMaster) { var app = cluster.fork(); app.on("message", function(code) { console.log("Parent received: " + code); app.send("this is from the test.js parent"); }); } else { process.send(""); process.on("message", function(code) { console.log("Child received: " + code); process.send("this is from the test.js child"); require("./testobj.js"); process.exit(0); }); }
testobj.js:
process.send("this is from testobj.js"); process.on("message", function(code) { console.log("testobj.js received: " + code); }); process.send("this is the second message from testobj.js"); while (true) {}
运行节点test.js时的结果
Parent received: Child received: this is from the test.js parent Parent received: this is from the test.js child Parent received: this is from testobj.js Parent received: this is the second message from testobj.js
现在看到我的工作到目前为止,目标是产生独立于父进程的subprocess,但仍保留双向通信。 到目前为止,testing代码保留了孩子对父母的沟通,但不是父母对孩子。 有没有人对如何保留或重build父母与子女的沟通有任何build议?
while(true){}
会永久冻结该子项的事件循环,尽pipeprocess.exit(0)
正在杀死分叉的worker并使其不再是永久的。 据我所知,你不能退出一个进程并保持通信(因为进程本质上不再运行)。
您应该能够通过添加更多事件侦听器来更轻松地查看正在发生的事情。 fork事件有一个体面的例子,虽然它将在您的app
variables,而不是引用的cluster
variables。
app.on('fork', function(worker) { console.log('Worker forked: ' + worker.id); console.log(worker); }); app.on('listening', function(worker, address) { console.log('Worker listening: ' + worker.id); console.log(address); }); app.on('exit', function(worker, code, signal) { console.log('Worker exited: ' + worker.id); console.log('Code: ' + code + ' Signal: ' + signal); });
基于worker.send文档/示例,似乎使用else if(cluster.isWorker)
而不是else
示例可能是个好主意:
if (cluster.isMaster) { var worker = cluster.fork(); worker.send('hi there'); } else if (cluster.isWorker) { process.on('message', function(msg) { process.send(msg); }); }
- Google身份validationcallback使用Node.js / Passport缺less范围错误
- 我收到错误“返回binding.PBKDF2(密码,盐,迭代,keylen,callback); ^ TypeError:不是一个缓冲区“
- 重新启动浏览器后,ngCookies不会保存cookie
- 使用mongoose的数据操作不起作用
- WebRTC上的信令通道
- Mongoose – find():search选项内的对象不起作用
- 在JavaScript中将文件/目录结构转换为“树”
- request.auth.session.set(user_info)不工作HapiJS
- 使用Promise保存多个文件