Scripts (running once)
Olaf Trygve Berglihn
olafb+usenet at pvv.org
Mon Jun 25 10:03:59 EDT 2001
Carsten Gaebler <clpy at snakefarm.org> writes:
> 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).
Good solution with fcntl.flock(), I forgot about race-conditions.
Storing the PID does not really work since PIDs are recycled (on Linux
PID is typically int). It is not highly likely that you will get the
same PID on the same program, but it can happen. It is also wise to
store the pid so that you can check for stale lock files on excecution
of the program, i.e. if the PID in the lock file does not exist, then
the lock file is stale and can be overwritten.
Olaf
--
Olaf Trygve Berglihn <olafb+usenet at pvv.org>
More information about the Python-list
mailing list