linuxでプロセスが存在するかどうかを検出する標準的な方法
1713 ワード
killコマンドで1つの信号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
投稿が私を助けてくれた
Jun 15 '10 at 10:58
前提条件プロセス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/signal �C Christoffer Hammarstrm Jun 15 '10 at 10:58