2014-02-24 57 views
1

第一代碼:如何產生獨立的孩子並重新建立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 

既然您看到我的工作到目前爲止,其目標是產生獨立於父代的子流程,但仍保留雙向通信。目前爲止的測試代碼保留了孩子與父母的溝通,但不是父母對孩子的溝通。 有沒有人對如何保留或重建父母與子女溝通有任何建議?

回答

1

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