<div>On Sun, Dec 27, 2009 at 4:42 PM, Dan Sommers <span dir="ltr"><<a href="mailto:somm1105@bellsouth.net">somm1105@bellsouth.net</a>></span> wrote:</div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="im">On Sun, 27 Dec 2009 19:07:12 -0500, python wrote:<br>
<br>
> Hans,<br>
><br>
>> Unfortunately, Windows is not a respectable OS. Unlike Unix, it allows<br>
>> two processes to bind to the same port. The theory is that this somehow<br>
>> allows the two processes to share their workload. One thing the OP can<br>
>> portably do, is try to connect() to the port. If that succeeds, then a<br>
>> server program is already running at that port, so he should exit.<br></div></blockquote><div><br></div><div>In this case, I think doing it in an OS-independant way just complicates life-- because you just gotta deal with the disrespected :) Some things are just easier to do the way a particular OS is built, and then let the rest of the platforms all do it another way. </div>
<div><br></div><div>Here's how we do it at the office:</div><div><div> if sys.platform == "win32":</div><div> from ctypes import windll</div><div> hMutex = windll.kernel32.CreateMutexA(None, 0, "COMPANY_PROGRAM_%s" % os.environ['USERNAME'])</div>
<div> if windll.kernel32.GetLastError() == 183:</div><div> sys.exit()</div><div><br></div></div><div>Where COMPANY and PROGRAM are strings which make the resulting string unique to this program. The reason I included username is in cases of people running my app in Terminal Services / Citrix or such where multiple people are on the machine at once-- my app is a user-app and not a server-app, so its fine to run multiple times on the one machine, what I really wanted to prevent was more then one user-per-machine. In your case its probably not necessarily.</div>
<div><br></div><div>The named mutex will exist in the system indefinitely and any subsequent attempts to create one of the same name will simply fail; and when your program closes-- for any reason-- Windows will automatically clean up the mutex.</div>
<div><br></div><div>Then on any other platform, the socket-binding has been a good solution for us for this need. I never quite liked the lockfile approach due to some bad experiences with stale-files, which isn't a problem for sockets and mutexes as they are automatically cleaned up by the OS (at least eventually) even after a hard and nasty crash. I don't know if Diez's approach is subject to that at all, granted-- if its not, awesome :)</div>
<div><br></div><div>Just posting as an FYI in case its interesting in posterity.</div><div><br></div></div><div name="mailplane_signature">--S</div>