views:

622

answers:

5

I need to find a right way to prevent two running instances of my (Python) program. I am currently using the following method.

On Windows,

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

On Linux,

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

It seems to work fine for now. Is this method correct? Can someone suggest to me a better way?

edit: Thanks for the reply guys, Is anything wrong with the above methods? I tried the pid file way for linux. What if the pid file gets deleted somehow?

+4  A: 

There are numerous ways:

  1. have an "instance file" in /var/run or similar (cross-platform)
  2. use a fixed socket (cross-platform)
  3. use DBus to register a name (linux)

What you need is a service (external to your application) that manages a namespace where unique ids are available & enforced.

jldupont
A: 

What you want to set us is a Singleton Pattern in your application.

Here's an article about setting one up in a python application.

Gordon
+1  A: 

For linux, see the answer from jldupont. For windows, use the CreateMutex-method, to create a named mutex. See: http://msdn.microsoft.com/en-us/library/ms686927%28VS.85%29.aspx

Sven Lilienthal
+2  A: 

on Linux, I used to write a pidfile, roughly:

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

lately, i´ve heard of the flock(1) tool. it´s easier to use in bash scripts:

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

and not too hard to use from 'real' programming languages, just open a file and try to get a flock(2) on it.

Javier
A: 

This is basically a duplicate of the python-single-instance-of-program question.

Peter Hansen
Well-spotted. But this should be a comment, not an answer.
ire_and_curses
Thanks for the guidance, ire_and_curses. It would be better when "training" us newbies to provide a link to the instructions, in this case perhaps http://meta.stackoverflow.com/questions/10841/how-to-handle-duplicate-questions
Peter Hansen
@Peter Hansen: A fair point.
ire_and_curses