Linux 检测Python程序是否存在并自动重启

stackoverflow上有一段脚本:

#! /bin/bash

case "$(pidof amadeus.x86 | wc -w)" in

0)  echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
    /etc/amadeus/amadeus.x86 &
    ;;
1)  # all ok
    ;;
*)  echo "Removed double Amadeus: $(date)" >> /var/log/amadeus.txt
    kill $(pidof amadeus.x86 | awk '{print $1}')
    ;;
esac

这段脚本写的很好,但是pidof不能检测python指定脚本的pid,只能检测python的pid,解决的办法是用pgrep。

str = $(pgrep -f "python /user/test.py")  

检测text.py的pid,如果有多个pid,注意它的输出为字符串,可以用arr=(${str// / })来分割成数组进行具体操作。

pgrep -f "python /user/test.py" | wc -w 

查看test.py的pid个数

改写后的脚本:

#! /bin/bash

case "$(pgrep -f "python /user/test.py" | wc -w)" in

0)  echo "Starting program:     $(date)" >> /var/log/test.txt
    python /user/test.py &
    ;;
1)  echo "Restarting program:     $(date)" >> /var/log/test.txt
    kill $(pgrep -f "python /user/test.py")
    python /user/test.py &    
    ;;
*)  echo "Removed double program and restarting: $(date)" >> /var/log/test.txt
    kill $(pgrep -f "python /user/test.py")
    python /user/test.py &
    ;;
esac

你可能感兴趣的:(linux)