Windows mutex to prevent multiple instances

Samuel Bronson neaesten at myrealbox.com
Wed Aug 28 17:45:24 EDT 2002


Hans Nowak wrote:
> 
> Howdy y'all,
> 
> In my current project, we have several programs that should not be run 
> multiple times simultaneously. To prevent this from happening, I used a 
> mutex, roughly like this (some irrelevant lines snipped):
> 
>         self.mutex = None
> 
>         try:
>             import win32event, win32api, winerror
>         except ImportError:
>             print "No win32all available"
>         else:
>             self.mutex = win32event.CreateMutex(None, 1, name)
>             lasterror = win32api.GetLastError()
>             if lasterror == winerror.ERROR_ALREADY_EXISTS:
>                 self.mutex = None
>                 raise SingleInstanceError
> 
> First instance of a program runs, second one raises SingleInstanceError 
> and quits.
> 
> Now, this works as expected, as long as I try it as the same user. (E.g. 
> I open two command lines, and try to start the same program in both.) 
> The situation on the production server is a bit different. A cron-like 
> service runs a batch file with the program every N minutes. However, 
> different users can log in and sometimes run the program by hand as 
> well, for troubleshooting. We were assuming that if the thing was 
> already running, they would get the error message, but this appears not 
> to be the case. Apparently it doesn't work for different 
> logins/users/processes or maybe it has something to with permissions.
> 
> So, my obvious question is, is there a way to make a "global mutex" to 
> prevent this from happening? The server runs Windows 2000.
> 
> TIA,
> 
   Use a lock file, you could call it 'myapp.pid' and put the pid of 
your app in it so it can serve double-duty.
   Obviously, you will need to have a path for it if you want it to 
actually work.
   You may also wish to consider why it is so important that only one 
instance exist at a time.
--SamB




More information about the Python-list mailing list