Auto-restart an process when it crashes

11,733

Given you control the init.d script to start this process you might want to just wrap the execution of your process in the init.d script like so:

until myserver; do
    echo "Server 'myserver' crashed with exit code $?.  Respawning.." >&2
    sleep 1
done

This will lanch your process in an until loop basically forever, each time it dies. Counting etc. could be introduced like this:

cnt=0
max=3
until myserver; do
    let cnt=cnt+1
    echo "Server 'myserver' crashed with exit code $?.  Respawning.." >&2
    sleep 1
    [ $cnt = $max ] && exit;
done
Share:
11,733

Related videos on Youtube

Mariano Martinez Peck
Author by

Mariano Martinez Peck

Updated on September 18, 2022

Comments

  • Mariano Martinez Peck
    Mariano Martinez Peck almost 2 years

    I have an app that I need to autostart when the OS starts. I am running in a CentOS 6, so I am using a LSB init script placed in /etc/init.d. So far this is fine and working.

    Now....besides that, what I would like is that if my app crashes (exits with error), I want that it automatically starts again. Ideally, even defining a max number of tries. In Mac's Info.plist there are the keys KeepAlive Since I already have chkconfig working, I was wondering if there is something I could do with it.

    I know there is http://mmonit.com/monit/ but it may be too much for what I need.

    • Bratchley
      Bratchley about 11 years
      This feature was added to systemd basically because it is such a hassle for admins to implement a third-party solution. If the application doesn't have its own monitoring process, there's nothing that supervises service continuity unless you install and configure something for that purpose.
    • Rahul Patil
      Rahul Patil about 11 years
      what is the issue with monit ?