473,396 Members | 2,036 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

translating "create Semaphore" to Linux

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
Aug 29 '08 #1
5 2710
GHUM 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.)
You might consider using a cooperative file locking for that. I do this as
follows:
#-------------------------------------------------------------------------------

class LockFileCreationException(Exception):
pass
#-------------------------------------------------------------------------------

class LockObtainException(Exception):
pass
#-------------------------------------------------------------------------------

class LockFile(object):

def __init__(self, name, fail_on_lock=False, cleanup=True):
self.name = name
self.cleanup = cleanup
try:
self.fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_APPEND)
except OSError, e:
if e[0] == 2:
raise LockFileCreationException()
self.file = os.fdopen(self.fd, "w")
lock_flags = fcntl.LOCK_EX
if fail_on_lock:
lock_flags |= fcntl.LOCK_NB
try:
fcntl.flock(self.file, lock_flags)
except IOError, e:
if e[0] == 11:
raise LockObtainException()
raise
def __enter__(self):
return self.file
def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb):
self.file.close()
# we are told to cleanup after ourselves,
# however it might be that another process
# has done so - so we don't fail in that
# case.
if self.cleanup:
try:
os.remove(self.name)
except OSError, e:
if not e[0] == 2:
raise
You can use the LockFile as context, and either block until the lock is
released (which is most probably not what you want), or fail with
LockObtainException.

Diez
Aug 29 '08 #2
On 29 Ago, 13:28, GHUM <haraldarminma...@gmail.comwrote:
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
Aug 29 '08 #3
GHUM wrote:
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.

Running a serious risk of teaching my grandmother, but...

.... why use a Semaphore rather than a Mutex? Or why not
simply use the bound socket as its own mutex? I know
Windows won't allow you to rebind the same socket to the
same addr/port in two different processes (unless perhaps
you play some trickery with the socket options).

TJG
Aug 29 '08 #4
Tim,
... why use a Semaphore rather than a Mutex?
as much as I understood the documentation at MSDN

http://msdn.microsoft.com/en-us/libr...27(VS.85).aspx
http://msdn.microsoft.com/en-us/libr...46(VS.85).aspx

a mutex seems to be nothing else than a special case of a semaphore?
That is, a semaphore can be created to allow MAX_SEM_COUNT concurrent
runners, and MUTEX defaults to one and only one ...

The other api-spells are identical, like wait_for_xxxx...; so propably
I stumbled on the working Semaphore Code before, or in some ancient
win32 wrapper createMutex was not documented or something in that
aspect:)
Or why notsimply use the bound socket as its own mutex? I know
Windows won't allow you to rebind the same socket to the
same addr/port in two different processes (unless perhaps
you play some trickery with the socket options).
My experience was that this is correct for certain values of "allow"
and "trickery". Sometimes the binding seems to get allowed but does
not work. Main reason is that the socket-bind happens somewhere in
medusa or <someotherhttpsserverframeworkiuse>; so to use it as a
semaphore I would have to dig there. I am not totally sure what
trickery on socket is played down there; and I prefer to stay as far
away as possible from that area.

Harald
Aug 29 '08 #5
GHUM wrote:
Tim,
>... why use a Semaphore rather than a Mutex?

as much as I understood the documentation at MSDN

http://msdn.microsoft.com/en-us/libr...27(VS.85).aspx
http://msdn.microsoft.com/en-us/libr...46(VS.85).aspx

a mutex seems to be nothing else than a special case of a semaphore?
That is, a semaphore can be created to allow MAX_SEM_COUNT concurrent
runners, and MUTEX defaults to one and only one ...

The other api-spells are identical, like wait_for_xxxx...; so propably
I stumbled on the working Semaphore Code before, or in some ancient
win32 wrapper createMutex was not documented or something in that
aspect:)
I think it hardly matters except that someone (like me :) )
coming to your code who's familiar with the uses of mutex
and semaphore elsewhere -- they're not Microsoft inventions
as I'm sure you realise -- will be a little stumped by the
fact that a mutex is pretty much the canonical recipe for
allowing only one instance of an app, yet you're using a
semaphore which can be used for slightly different
purposes. I'd be wondering whether you had some more
sophisticated model in mind which I was unable to fathom...
>
>Or why notsimply use the bound socket as its own mutex? I know
Windows won't allow you to rebind the same socket to the
same addr/port in two different processes (unless perhaps
you play some trickery with the socket options).

My experience was that this is correct for certain values of "allow"
and "trickery". Sometimes the binding seems to get allowed but does
not work.
Fair enough.

TJG
Aug 29 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: niku | last post by:
Hello all. I'm trying to get mysql installed on OpenBSD 3.4. Unfortunately, it appeares that the port only installes the mysql-client, and one needs to install the -server package seperately. This...
2
by: Robin Tucker | last post by:
I have some code that dynamically creates a database (name is @FullName) and then creates a table within that database. Is it possible to wrap these things into a transaction such that if any one...
8
by: cainlevy | last post by:
I'm wondering if there's any way to speed up create table queries? Besides upgrading hardware, that is. The very simplest table creation query, "create table table1 ( field1 INT(10))" is taking...
0
by: jesper.hvid | last post by:
Hi. I've noticed, after moving some of our code to 2.0, that System.Net.WebRequest.Create(System.String) and System.Uri(System.String) no longer behave as they did in 1.1 framework. Example:...
7
by: alessandro menchini | last post by:
Hello, First of all: i apologize for my english...i'm still learning... If i create a view it seems that DB2 manage this view like an updateable view. But I need to create a view "read only",...
1
by: dave.j.thornton | last post by:
I'm attempting to create a new table, and populate it using the fields from two existing tables. The code is printed below. I get the error: "Run-time error '-2147217900 (80040e14)': Syntax error...
0
by: vaibhavsumant | last post by:
<project name="DBCreate" default="usage" basedir="."> <property name="user" value="db2admin"/> <property name="passwd" value="db2admin"/> <property name="dbprefix" value=""/> <property...
6
by: maanasa | last post by:
hi, i've one question. I'm supposed to create oracle user on click of a button using oracle forms. I'm calling a procedure which i've written in sql+ which is supposed to create the user. The...
3
by: Evan | last post by:
Hello, one of my PC is window system, and in "control panel -Network Connections", I can see some network connections such as PPPOE or VPN which I created by click "create a new connection". ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.