2011-04-06 80 views
0

是否有可能使用Node.JS獲取父進程ID?我想檢測父母是否被殺害或者以不能通知孩子的方式失敗。如果發生這種情況,孩子的父進程ID應該變爲1.Node.JS父進程ID

這會優於需要父級定期發送保持活動狀態的信號,並且最好還是運行ps命令。

+0

你使用系統「兒童進程?」 – Emmerman 2011-04-06 12:06:04

+0

@Emmerman:我不確定你的意思。父節點運行'require('child_process')。spawn(process.argv [0],['path_to_child.js'])'以啓動子節點。然後,如果需要與孩子交談,則使用孩子的標準輸入和標準輸出。 stderr被傳送到日誌。我猜測答案是肯定的? – 2011-04-06 12:11:15

回答

5

您可以使用pid文件。這樣

var util = require('util'), 
    fs = require('fs'), 
    pidfile = '/var/run/nodemaster.pid'; 

try { 
    var pid = fs.readFileSync(pidfile); 
    //REPLACE with your signal or use another method to check process existence :) 
    process.kill(pid, 'SIGUSR2'); 
    util.puts('Master already running'); 
    process.exit(1); 
} catch (e) { 
    fs.writeFileSync(pidfile, process.pid.toString(), 'ascii'); 
} 

//run your childs here 

東西你也可以在spawn()通話

0

我從原生OSX應用程序作爲後臺工作內開始發送的Node.js PID作爲參數。爲了使Node.js的退出時消耗node.js的標準輸出父進程死亡/退出,我做了以下內容:

// Watch parent exit when it dies 

process.stdout.resume(); 
process.stdout.on('end', function() { 
 process.exit(); 
}); 

容易這樣,但我不能完全肯定,如果這是你經歷了什麼要求;-)