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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章