簡體   English   中英

如何生成獨立的子代並在node.js中重新建立通信?

[英]How do I spawn independent children and re-establish communication in 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

到目前為止,您已經了解了我的工作,目標是生成獨立於父代的子流程,但仍保留雙向通信。 到目前為止,該測試代碼保留了子對父之間的通信,但不保留子對父之間的通信。 是否有人對如何保留或重新建立父母與孩子之間的溝通有任何建議?

while(true){}永久凍結了該孩子的事件循環,盡管process.exit(0)殺死了派生的工作者,但使其不再那么永久。 據我所知,您不能退出進程並保持通信(因為該進程實際上不再運行)。

通過添加更多事件偵聽器,您應該能夠更輕松地查看正在發生的情況。 fork事件有一個不錯的示例,盡管它在您的app變量而不是引用的cluster變量上。

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);
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM