Re: [問題] 如何讓程式同時只能跑一隻

看板Python作者 (carl)時間13年前 (2012/07/27 10:15), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串3/5 (看更多)
看其他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
完整的方法要加一些配套, 例如有偵測到 pid 檔案時要嘗試
07/27 21:49, 3F

07/27 21:49, , 4F
與那個 process 通訊, 如果收不到回應就認定是不正常關閉
07/27 21:49, 4F
喔喔 所以在檔案裏面放的pid 應該是用來檢查用的吧 可以拿這個pid去/proc/底下檢查 我把程式修了一下~~ 資料是參考這邊的 http://stackoverflow.com/questions/38056 ※ 編輯: carlcarl 來自: 59.127.237.167 (07/27 23:44)
文章代碼(AID): #1G4cfIHA (Python)
討論串 (同標題文章)
文章代碼(AID): #1G4cfIHA (Python)