Singleton process

Francis Avila francisgavila at yahoo.com
Mon Dec 22 01:44:20 EST 2003


Fortepianissimo wrote in message ...
>Here is the situation: I have multiple processes of same Python script
>fired, but I want *only one* of them to continue and all the others to
>quit immediately.
>
>I can use a lock file, and the first process will get the necessary
>lock. But if I do open(lockfile) all the other subsequent processes
>will just wait there - instead I want them to quit immediately.
>
>Can someone give a simple outline of how to achieve this? Thanks a
>lot.

This seems like a very strange requirement.  May I ask why you're doing
this?

Anyway, if you're using a lock file, how is 'open' going to help you?  Open
opens a file, creating it if it does not exist.  Think about how a lockfile
would work in your situation:

- If the lockfile exists, terminate myself.
- Otherwise, create the file (thus grabbing the lock).
- Make sure somebody deletes the file when done.

Do the first with os.access('filename', os.F_OK)
Do the second with file('filename').close(). (or use os.open if you are
worried about being atomic.)
Do the third with os.unlink('filename'), if the Python process is supposed
to clean up after itself.  You might want to put this into the exit signal
handler.
--
Francis Avila





More information about the Python-list mailing list