translating "create Semaphore" to Linux

Francesco Bochicchio bockman at virgilio.it
Fri Aug 29 08:11:52 EDT 2008


On 29 Ago, 13:28, GHUM <haraldarminma... at gmail.com> wrote:
> hello,
>
> in my application I am using
>
> hSem = win32event.CreateSemaphore (None, 1,
> 1,"stringincludinginterfaceandport")
> rt=win32event.WaitForSingleObject (hSem, 0)
> if rt != win32event.WAIT_TIMEOUT:
>    really_do_start_my_app()
> else:
>    print "application allready running"
>
> to make sure that only ONE instance of the application is running at a
> time. (as it implements a local webserver, that is necessary. Two
> webservers listening on one port is bad)
>
> Now I am going to make this application run on Linux. How can I get
> similiar behaviour on Linux?
>
> I know of the .pid files that get written by some server processes ...
> BUT they do not get cleaned up on unclean shutdown of the application.
>
> is there some better method?
>
> Or some module which wraps the details of .pid-files quite nicely?
> (like "trying to remove to check if other instance is still
> running...., failing properly on missing write privs etc.)
>
> best wishes,
>
> Harald

The best way I know to do it is to use fnctl.flock or fcntl.lockf
functions. I never used it, so can just point you to the
official documentation. The idea is that your applications should take
exclusive access to one of the application files, so that if it is
started a second time, the second run will find the file locked and
understand that there is an instance started.
AFAIK, if the process locking a files dies, the OS releases the lock,
so there is no possibility of stale locks (check this!).

Anyway, you could simply use your server socket as lock. It is not
possible to have two processes accepting connections on the same port,
the second process would receive an error 'Address already in use'.
You could use it as signal that there is
already an instance of the application running. This method should be
available in both Windows and Linux (and various
Unix flavours too), so your code would be more portable.

Ciao
----
FB



More information about the Python-list mailing list