Re: [問題] 如何讓程式同時只能跑一隻
看其他deamon的作法是建立一個xxx.pid的檔案 然後將pid寫到裏面
所以我跟著這樣做
sleep是開一段時間 用來驗證再次開同樣process用的
檢查我就只單純檢查檔案存不存在而已
然後要用root執行
不然可以在開始先建立好一個資料夾
權限設好後 pid的檔案就建立在裏面 這樣就可以不用root權限
#!/usr/bin/env python
# coding: utf-8
import sys
import os
import time
if __name__ == '__main__':
if os.path.exists('/var/run/test.pid'):
f = open('/var/run/test.pid')
s = f.readline()
if not os.path.exists('/proc/' + s):
os.remove('/var/run/test.pid')
print 'The process may crashed before'
else:
sys.exit('Error!')
p = os.getpid()
f = open('/var/run/test.pid', 'w')
f.write(str(p) + '\n')
f.close()
time.sleep(20)
os.remove('/var/run/test.pid')
--
http://blog.carlcarl.tw
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.127.237.167
推
07/27 20:56, , 1F
07/27 20:56, 1F
→
07/27 20:56, , 2F
07/27 20:56, 2F
→
07/27 21:49, , 3F
07/27 21:49, 3F
→
07/27 21:49, , 4F
07/27 21:49, 4F
喔喔 所以在檔案裏面放的pid 應該是用來檢查用的吧
可以拿這個pid去/proc/底下檢查
我把程式修了一下~~
資料是參考這邊的 http://stackoverflow.com/questions/38056
※ 編輯: carlcarl 來自: 59.127.237.167 (07/27 23:44)
討論串 (同標題文章)
完整討論串 (本文為第 3 之 5 篇):