Bash脚本在出现错误时重新启动程序 [英] Bash script to re-launch program in case of failure error

查看:67
本文介绍了Bash脚本在出现错误时重新启动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在linux(我使用Ubuntu)中,我运行了一个(红宝石)程序,该程序整天连续运行.我的工作是监视程序是否失败,如果失败,请重新启动程序.只需按一下"Up"作为上一个命令,然后按"Enter"即可.很简单.

In linux (I use a Ubuntu), I run a (ruby) program that continually runs all day long. My job is to monitor to see if the program fails and if so, re-launch the program. This consists up simply hitting 'Up' for last command and 'Enter'. Simple enough.

必须有一种方法可以编写bash脚本来监视程序是否停止运行并自动重新启动.

There has to be a way to write a bash script to monitor my program if its stops working and to re-launch it automatically.

我该怎么做?

奖励是能够在程序出错时保存程序的输出.

A bonus is to be able to save the output of the program when it errors.

推荐答案

您可以做什么:

#!/bin/bash
LOGFILE="some_file.log"
LAUNCH="your_program"

while :
do
    echo "New launch at `date`" >> "${LOGFILE}"
    ${LAUNCH} >> "${LOGFILE}" 2>&1 &
    wait
done

另一种方法是定期检查PID:

Another way is to periodicaly check the PID:

#!/bin/bash
LOGFILE="some_file.log"
LAUNCH="your_program"

PID=""
CHECK=""

while :
do
    if [ -n "${PID}" ]; then
        CHECK=`ps -o pid:1= -p "${PID}"`
    fi

    # If PID does not exist anymore, launch again
    if [ -z "${CHECK}" ]; then
        echo "New launch at `date`" >> "${LOGFILE}"

        # Launch command and keep track of the PID
        ${LAUNCH} >> "${LOGFILE}" 2>&1 &
        PID=$!
    fi

    sleep 2
done

这篇关于Bash脚本在出现错误时重新启动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆