【问题标题】:How to make this server process run forever?如何让这个服务器进程永远运行?
【发布时间】:2023-03-27 17:00:01
【问题描述】:

我有这个使用 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

【问题讨论】:

  • 为什么/在哪里/如何崩溃?
  • 它因未分配一些无效变量而崩溃(一些代码错误,因为服务器脚本很大,我们想暂时使其自动重启)

标签: javascript node.js bash centos


【解决方案1】:

如果您使用的是新的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-03
    • 2014-12-02
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多