我有一個運行在實時服務器上的 nodejs 應用程式。我通過 SSH 訪問服務器,在 VSCODE 的終端中使用以下命令啟動一個新的節點行程。
nohup node filename.js &
大多數情況下,我可以在 VSCODE 終端中使用以下命令查看行程 ID。
netstat -lpn | grep 30001
此命令提供以下輸出:
tcp6 0 0 :::30001 :::* LISTEN 21552/node
但是,有時它不會顯示任何行程 ID,如以下輸出所示:
tcp6 0 0 :::30001 :::* LISTEN -
如果行程因某些技術錯誤而終止,它應該會自動重新啟動。為此,我每 5 分鐘通過一次 cron 執行以下代碼,這是有效的。
const find = require('find-process');
var spawn = require('child_process').spawn;
find("port", "30001")
.then((list)=> {
console.log("list::", list);
if (!list.length) {
spawn('node', [`${__dirname}/filename.js`], {
detached: true,
stdio: 'ignore'
}).unref();
}
}, function (err) {
console.log(err.stack || err);
});
以下是我的 cron
*/5 * * * * node path-to-js-file/crontab.js
我的問題:
- 為什么我在埠 30001 上的節點實體有時沒有 pid 而其中包含的應用程式仍然可以訪問?
kill -9將需要一個我沒有的行程 ID,如上所示。如何通過命令殺死這樣的行程以便它可以重新啟動?
uj5u.com熱心網友回復:
要顯示程序,pid您可以使用processnodejs 模塊。
var process = require('process');
console.log(`Process pid ${process.pid}`);
uj5u.com熱心網友回復:
您可以通過process.pid. 類似地,當您使用 spawn 或 exec 創建子行程時,它回傳子行程物件并且此物件包含子父 ID
const find = require('find-process');
var spawn = require('child_process').spawn;
find("port", "30001")
.then((list)=> {
console.log("list::", list);
if (!list.length) {
const childProcess = spawn('node', [`${__dirname}/filename.js`], {
detached: true,
stdio: 'ignore'
}).unref();
console.log(`Child Process ${childProcess.pid}`);
}
}, function (err) {
console.log(err.stack || err);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/382643.html
