簡體   English   中英

'exit' - 在node.js集群中從master中殺死的工作進程中的事件

[英]'exit'-Event in worker process when killed from master within a node.js cluster

我想優雅地從主進程退出子進程,其中主代碼和子代碼在不同的.js文件中。

master.js

cluster.setupMaster({
  exec : 'child.js',
  args : [],
  silent : false
});
cluster.fork({'some': 'info'});

process.on('SIGINT', function() {
  console.log('\nshutting down services ...');
  function eachWorker(callback) {
    for (var id in cluster.workers) {
      callback(cluster.workers[id]);
    }
  }
  eachWorker(function(worker) {
    worker.kill();
  });
  process.exit(0);
})

child.js

cluster.worker.on('disconnect', function() {
  console.log(cluster.worker.id + ' shutting down.');
})

我嘗試了各種信號,cluster.worker.on('exit'),process.on('exit'),process.on('disconnect')等,但似乎沒有觸發。 有任何想法嗎?

worker.send()在執行期間工作,但不在SIGINT函數內?

Node.js(或我的Mac)似乎處理ctrl-c和SIGINT略有不同。 當我ctrl-c在主進程退出之前強制退出兩個子進程。 如果我在后台啟動master.jskill -SIGINT [pid] ,代碼會正確執行,孩子會收到通知,並且一切都很好。

您可以采取一些措施來解決這種情況。 第一種是使用SIGINT而不是ctrl-c實際殺死。 第二個是向子進程添加process.on('SIGINT') 簡單的東西:

process.on('SIGINT', function() {
    console.log('\nshutting down ...');
    setTimeout(function() { console.log('quitting'); process.exit(0); }, 10000);
});

會給孩子們適當的時間關閉。 (顯然目標是在10秒內退出)

要處理您想要的客戶端上的消息:

var cluster = require('cluster');
var worker = cluster.worker;
worker.on('message', function(msg) {
        console.log("message for worker: " );
        console.log(msg);
        if (msg == "exit) ...
});

在你的eachWorker(function...

worker.send("exit");

這可能實際上是node.js中的錯誤的結果。 集群仍然是“實驗性的”

暫無
暫無

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

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