3

I have a python program that has to be running all the time. If for some reason it was stopped I want to restart it automatically. I thought of having a cron that will run every n number of seconds and check the program is running. My shell script is looks like this:

#!/usr/bin/env bash
CM_COMMAND=`ps aux| grep abc| grep def| grep sudo`
LEN_COMMAND=${#CM_COMMAND}
if[["$LEN_COMMAND" -le "5"]] 
then
    echo "start the python program"
fi
exit

When I run this script I am getting the error: my_prog.sh: line 4: $'if[[118\r -le 5]]\r': command not found'

What is the alternative of doing this and what is the problem with my script?

9
  • One problem is that when somebody runs 6 arbitrary sudo commands matching your greps, your script will not be restarted. Commented Mar 21, 2018 at 11:38
  • Does the python process need to be running constantly, or is it enough to invoke it at a certain (higher frequency) interval? How fast does it have to restart to fulfil its purpose? Commented Mar 21, 2018 at 11:43
  • ps aux| grep abc| grep def| grep sudo if abc is program_name Commented Mar 21, 2018 at 11:43
  • The process has to be running constantly Commented Mar 21, 2018 at 11:44
  • It has to be running all the time without any stop. If it stops it needs to be restarted as soon as possible. Commented Mar 21, 2018 at 11:46

2 Answers 2

6

Maybe this would be more robust?

1) save the PID of your process when you start it with:

{your_python_command} & echo $! >>/{some_folder}/your_app.pid

2) This script will check and restart if it can't find the PID..

#!/usr/bin/env bash

PID=`cat /{some_folder}/your_app.pid`

if ! ps -p $PID > /dev/null
then
  rm /{some_folder}/your_app.pid
  {your_python_command} & echo $! >>/{some_folder}/your_app.pid
fi

3) To add it to a cronjob:

crontab -e

choose your text editor and add this row at the end of the file:

*/1 * * * * /{your_path}/{your_script_name}

exit and save

(this will run the script every minute, check crontab manual to set your exact interval)

Sign up to request clarification or add additional context in comments.

1 Comment

if you put it in a cronjob it will get activated automatically on reboot though the cronjob regardless of where you put the script - is that what you're after?
3

How about making it a service? A very clean solution, in my opinion.

For more information on how to do it, you can read this article.

Comments

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.