[英]How to avoid multiple instances of a program?
我需要找到一種正確的方法來阻止我的(Python)程序的兩個運行實例。 我目前正在使用以下方法。
在Windows上,
os.popen('wmic process get caption,processid | findstr `programname.exe`')
在Linux上,
os.popen('ps x | grep `programname`')
它似乎現在工作正常。 這種方法是否正確? 有人可以向我建議一個更好的方法嗎?
編輯:感謝回復家伙,上述方法有什么問題嗎? 我嘗試了linux的pid文件方式。 如果pid文件以某種方式被刪除怎么辦?
有很多方法:
您需要的是一個服務(在您的應用程序外部),它管理一個名稱空間,其中可以使用和執行唯一ID。
在Linux上,我曾經寫過一個pid文件,粗略地說:
if (pidfile already exists)
read pidfile content
if (/proc/<pid>/exec == my executable)
already running, exit
else
it´s a stale pidfile, delete it
write my own pid to pidfile
start the 'real' work
最近,我聽說過flock(1)工具。 它在bash腳本中更容易使用:
( flock -n 200 || exit
# ... commands executed under lock ...
) 200>/var/lock/mylockfile
並且不太難以使用“真正的”編程語言,只需打開一個文件並嘗試在其上獲得一個群(2) 。
對於linux,請參閱jldupont的答案。 對於Windows,請使用CreateMutex方法創建命名互斥鎖。 請參閱: http : //msdn.microsoft.com/en-us/library/ms686927%28VS.85%29.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.