2009-12-14 43 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)

相关问题