2009-12-14 41 views
7

我需要找到一個正確的方法來阻止我的(Python)程序的兩個正在運行的實例。 我目前使用以下方法。如何避免程序的多個實例?

在Windows上,

os.popen('wmic process get caption,processid | findstr `programname.exe`') 

在Linux上,

os.popen('ps x | grep `programname`') 

它似乎現在工作得很好。這種方法是否正確? 有人可以給我一個更好的方法嗎?

編輯:感謝回覆球員, 上述方法有什麼問題嗎? 我嘗試了linux的pid文件方式。如果pid文件被刪除了怎麼辦?

+1

Duplicate:http://stackoverflow.com/questions/380870/python-single-instance-of-program – 2009-12-14 16:18:52

+0

相關:http://stackoverflow.com/questions/220525/ensuring-a-single-instance-of -an-application-in-linux#221159 – 2009-12-14 16:20:01

+0

這基本上是[python-single-instance-of-program]的副本(http://stackoverflow.com/questions/380870/python-single-instance-of-程序)問題。 – 2009-12-14 15:55:09

回答

5

有許多方法:

  1. 在/ var/run中或類似的(跨平臺) 「實例文件」
  2. 使用固定插座(跨平臺)
  3. 使用的DBus註冊一個名字(linux)

你需要的是一個服務(在你的應用程序的外部)管理一個名字空間,其中唯一的ID可用&強制執行。

1

在Linux上,我以前寫一個pidfile進程文件,大致有:

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)工具。 it's更容易在bash腳本中使用:

(flock -n 200 || exit 
    # ... commands executed under lock ... 
) 200>/var/lock/mylockfile 

,而不是太難的「真實」的編程語言使用,只需打開一個文件,並嘗試得到它一個flock(2)

相關問題