linux下检测进程是否存在的标准做法

用kill命令发送一个信号0去检测,别用ps -ef pid|grep,会有误判的存在!

先决条件.进程id要写入pid文件,python做法

def write_pidfile(pidfile):
   if os.path.isfile(pidfile):
       with open(pidfile, ‘r‘) as f:
           old_pid = f.readline()
           if old_pid:
               old_pid = int(old_pid)
               try: os.kill(old_pid, 0)
               except: pass
               else: return False
   with open(pidfile, ‘w+‘) as f:
       f.write("%d" % os.getpid())
   return True


然后使用$?表示上一个命令的执行结果是否正常退出(非0)则表示进程信号0已经发布过去,进程不存在。

#!/bin/bash
PID_FILE="/home/machen/search_correct/data/search_correct.pid"
if [ -e $PID_FILE ];
then
   PID=`cat $PID_FILE`
   kill -0 $PID;  #check if process id exists
   if [ ! $? -eq 0 ];  #don‘t exists, boot one
   then
       /usr/local/bin/python2.7 /home/machen/search_correct/main.py -l
   else
       echo "process pid: $PID still exists. wait ..."
   fi
fi






帖子帮助了我

kill is somewhat misnamed in that it doesn‘t necessarily kill the process. It just sends the process a signal. kill $PID is equivalent to kill -15 $PID, which sends signal 15, SIGTERM to the process, which is an instruction to terminate. There isn‘t a signal 0, that‘s a special value telling kill to just check if a signal could be sent to the process, which is for most purposes more or less equivalent to checking if it exists. See linux.die.net/man/2/kill and linux.die.net/man/7/signalChristoffer HammarstrmJun 15 ‘10 at 10:58


linux下检测进程是否存在的标准做法

上一篇:明天的重点工作


下一篇:DFSR troubleshooting