linux - 在linux上启动了两个 Node 实例

标签 linux node.js cron

我有一个 node.js 服务器应用程序,由于某种原因启动了两次。我有一个每分钟运行一次的 cronjob,检查 node main.js 进程,如果没有找到,则启动它。 cron 看起来像这样:

* * * * * ~/startmain.sh >> startmain.log 2>&1

startmain.sh 文件如下所示:

if ps -ef | grep -v grep | grep "node main.js" > /dev/null
then
        echo "`date` Server is running."
else
        echo "`date` Server is not running! Starting..."
        sudo node main.js > main.log
fi

存储 startmain.js 输出的日志文件显示:

Fri Aug  8 19:22:00 UTC 2014 Server is running.
Fri Aug  8 19:23:00 UTC 2014 Server is running.
Fri Aug  8 19:24:00 UTC 2014 Server is not running! Starting...
Fri Aug  8 19:25:00 UTC 2014 Server is running.
Fri Aug  8 19:26:00 UTC 2014 Server is running.
Fri Aug  8 19:27:00 UTC 2014 Server is running.

这正是我所期望的,但是当我查看进程时,似乎有两个正在运行。一种在 sudo 下,一种不使用 sudo。查看前两个进程:

$ ps -ef | grep node
    root 99240 99232   0 19:24:01 ?           0:01 node main.js
    root 99232  5664   0 19:24:01 ?           0:00 sudo node main.js
   admin  2777 87580   0 19:37:41 pts/1       0:00 grep node

事实上,当我查看应用程序日志时,我发现启动条目重复出现。要终止这些进程,我必须使用 sudo,即使对于不以 sudo 开头的进程也是如此。当我杀死其中一只时,另一只也会死。

知道为什么我要启动两个进程吗?

最佳答案

首先,您在脚本 startmain.sh 中使用 sudo 启动 node main.js 应用程序。根据sudo man page :

When sudo runs a command, it calls fork(2), sets up the execution environment as described above, and calls the execve system call in the child process. The main sudo process waits until the command has completed, then passes the command's exit status to the security policy's close method and exits.

因此,在您的情况下,名为 sudo node main.js 的进程是 sudo 命令本身,进程 node main.js 是 node.js 应用程序。您可以轻松验证这一点 - 运行 ps auxfw,您将看到 sudo node main.js 进程是 node main.js 的父进程。

验证这一点的另一种方法是运行 lsof -p [process id] 并查看进程 sudo node main.jstxt 部分状态 /usr/bin/sudo,而进程 node main.jstxt 部分将显示 node 二进制文件的路径。

最重要的是,您不必担心您的 Node.js 应用程序会启动两次。

关于linux - 在linux上启动了两个 Node 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25211122/

相关文章:

linux - 树莓派有静态IP地址

json - 循环遍历 JSON 中具有相同属性的未知标识符(和未知数量)

date - 如何更改tomcat服务器日期?

node.js - MongoDB聚合期间的"Server x timed out"

node.js - NodeJS - 如何检查 Gzip 压缩是否正常工作?

php - 每 24 小时运行一次 php 任务

amazon-web-services - Cloudwatch 自定义指标 - 内存利用率 --from-cron 不起作用

linux - BASH:将大小与另一个文件大小的百分比部分进行比较

html - Nawk 脚本在 HTML 表上的错误输出

java - 为什么你必须为 Windows 和 Linux 编写单独的程序