如何让这个服务器进程永远运行?

时间:2014-11-03 01:42:42

标签: javascript node.js bash centos

我有这个使用nodejs运行的Javascript Signal服务器。

但是每天它都会崩溃,因此整个服务都会崩溃。我正在使用以下无限循环来重新启动nodejs脚本,如果它已崩溃或未运行。但它并不完美。

任何人都可以优化它,或者是否有更好的方法来保持a.js一直运行,如果突然进程没有活着的话。

#!/bin/bash
while :
do
  # 1
  videoupload=$(pgrep -f "a.js")
  if [ $videoupload ]; then
    log1="running a $1 $2"
  else
    log1="re-launch a $1 $2"
    nohup node /var/tmp/signal/a.js 2>&1 | tee -a /var/tmp/signal.log &
  fi

  echo $log1
  sleep 1
done

1 个答案:

答案 0 :(得分:2)

如果您正在使用新的CentOS 6,更好的方法是将其置于Upstart脚本中。 Upstart监视所有系统守护进程并确保它们保持运行。下面的Upstart配置也将在系统启动时启动您的进程。

编辑文件/etc/init/a.conf并将以下配置放入其中。您需要sudo以root身份进行编辑。

description "a.js"
author "YumYumYum"


# Stanzas
#
# Stanzas control when and how a process is started and stopped
# See a list of stanzas here: http://upstart.ubuntu.com/wiki/Stanzas#respawn

# When to start the service
start on runlevel [2345]

# When to stop the service
stop on runlevel [016]

# Automatically restart process if crashed
respawn


script
  echo $$ > /var/run/a.pid;
  exec node /var/tmp/signal/a.js
end script


post-stop script
  rm -f /var/run/a.pid
end script

现在您已为流程创建了Upstart配置,您可以从命令行启动它:

$ sudo service a start

Upstart将监控您的流程,并在任何时候停止运行。它还会将日志重定向到/var/log/upstart/a.log

相关问题