【问题标题】:nodejs how to find the process idnodejs如何找到进程id
【发布时间】:2022-01-17 18:56:42
【问题描述】:

我有一个在实时服务器上运行的 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

我的问题:

  1. 为什么我在端口 30001 上的节点实例有时没有 pid,而其中包含的应用程序仍然可以访问?
  2. kill -9 将需要一个我没有如上所示的进程 ID。如何通过命令杀死这样的进程以便重启?

【问题讨论】:

    标签: node.js linux server process


    【解决方案1】:

    要显示进程pid,你可以使用nodejs的process模块。

    var process = require('process');
    console.log(`Process pid ${process.pid}`);
    

    【讨论】:

    • 您好,感谢您的回复,但我的查询是关于了解 SHELL 中的进程 ID,而不是节点中的进程 ID。节点已经通过 cron 处理它。但是如果我需要通过 SHEL 中的 kill -9 重新启动实例,我没有 pid。另外,为什么 pid 不能通过 SHELL 命令获得?
    • @ITSagar 您可以使用推荐 ps 在 shell 中看到 pid
    猜你喜欢
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 2011-07-14
    • 2012-07-12
    相关资源
    最近更新 更多