How do I force a single instance of a python app?

Grant Edwards grante at visi.com
Fri Oct 27 13:20:35 EDT 2000


In article <8t54f9$9r4$1 at drmanhattan.kryogenix.org>, Aquarius wrote:

>You *could* sort of hack a file-existence thing that makes the first
>instance write the current time to the file every minute or so; if an
>instance fires and finds the flag file, but the time in it is more than a
>minute old, then you know that an instance ran but died before it could
>delete the file, and you're safe to start. This does mean that you're
>unable to start a second instance within a minute of the first instance
>dying incorrectly, which might cause a problem.

The standard method uder Unix is: create a lockfile and write
your PID into it.  If the create fails because the file exists,
then open the file and read the PID.  Verify that the process
is running -- if not, remove the file and try again.

There are two problems (under Unix) with this approach:

 1) Checking for the existance of a process given the PID isn't
    a trivial thing to do in a portable way (even between Unix
    systems).

 2) PIDs roll over, so there's a remote chance that the process
    that created the lock file crashed without deleting it, and
    weeks and weeks later some other unlreated process is
    running with that same PID.  This could make it appear that
    the lock file is valid when it isn't.
    
Other possible problems:

 1) I don't know if file creation is an atomic operation on
    non-Unix systems.
    
 2) I don't know if all systems have PIDs that can be used in
    this way.

-- 
Grant Edwards                   grante             Yow!  Yow! Are we laid
                                  at               back yet?
                               visi.com            



More information about the Python-list mailing list