Scripts (running once)

Carsten Gaebler clpy at snakefarm.org
Mon Jun 25 09:28:20 EDT 2001


Olaf Trygve Berglihn wrote:

[how to keep a program from running more than one instance simultaneously]

> #!/usr/bin/env python
[...]
>         if os.path.isfile(LOCKFILE):
>                 import sys
>                 sys.stdout.write("Already running myprog\n")
>                 sys.exit(1)
>         else:
>                 fd = open(LOCKFILE, 'w')
>                 fd.close()
[...]

This will not really work if the two processes are *started* at the same
time. I.e. process 1 calls isfile() which returns 0. Then the OS switches
to process 2 which also get a 0 from isfile(). You'll end up with two
processes running at the same time.

Better really lock the file by calling fcntl.flock() right after open()
(blocking or nonblocking, whatever is suitable), or by storing the process
id in the lock file and checking if that process id is still hanging
around (e.g. via /proc on Unix).

cg.



More information about the Python-list mailing list