简体   繁体   中英

How do I spawn independent children and re-establish communication in node.js?

First the code:


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

The result when running node 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

Now that you see my work so far, the goal is to spawn sub processes independent of the parent but still retain two-way communications. The test code so far retains child to parent communication, but not parent to child. Does anyone have any suggestions on how to retain or re-establish parent to child communication?

The while(true){} is freezing that child's event loop permanently, though the process.exit(0) is killing the forked worker and making it no so permanent. As far as I know, you cannot exit a process and retain communication (since the process is no longer running essentially).

You should be able to more easily see what is transpiring by adding some more event listeners. The fork event has a decent example, though it would be on your app variable instead of the referenced cluster variable.

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

Based on the worker.send documentation / example, it seems it might be a good idea to use an else if(cluster.isWorker) instead of just else per the example:

if (cluster.isMaster) {
  var worker = cluster.fork();
  worker.send('hi there');
} else if (cluster.isWorker) {
  process.on('message', function(msg) {
    process.send(msg);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM