1

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.

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.

How would I go about doing this?

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

1
  • While suggested answers are simple and will definitely work, you may consider to use specialized software for supervising your program. Like supervisor or look here for more alternatives. Commented Feb 11, 2016 at 8:43

2 Answers 2

2

What you could do:

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

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

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
Sign up to request clarification or add additional context in comments.

Comments

1

Infinite loop:

while true; do
  your_program >> /path/to/error.log 2>&1 
done

2 Comments

Usually it is wise to add a sleep 1 after the invocation of the program to be gentle on the box if your_program is spin looping (eg, crashing quickly and repeatedly)
@WilliamPursell: This is a useful addition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.