slloyd has asked for the wisdom of the Perl Monks concerning the following question:

I suggest Win32::Mutex as a way to guarantee only one instance of your Win32 program runs at a time. I have been using Win32::Semaphore but have learned that Inno Setup supports Mutexes (AppMutex). This allows my install to detect if my program is already running during install/uninstall and prompts the user to first shut down the app before continuing. For the benefit of others that may have the same need, I have included code for both.

Mutex Code

#!perl -w use strict; $|=1; use Win32::Mutex; my $mutexname="PIGMania"; if(Win32::Mutex->open($mutexname)){ print "must be already running"; exit; } my $mutex=Win32::Mutex->new(1,$mutexname); $mutex->wait(3); print "Mutex: $mutex\n"; my $x=30; while($x){ print "."; select(undef,undef,undef,1.5); $x--; }

Semaphore Code

#!perl -w use strict; $|=1; use Win32::Semaphore; my $semaphore_name="PIGMania"; if(Win32::Semaphore->open($semaphore_name)){ print "$semaphore_name is already running\n"; exit; } my $semaphore=Win32::Semaphore->new(1,1,$semaphore_name); print "Semaphore: $semaphore\n"; my $x=30; while($x){ print "."; select(undef,undef,undef,1.5); $x--; }

-------------------------------
Need a good Perl friendly Host Provider?
http://www.dreamhost.com

Replies are listed 'Best First'.
Re: Using Win32::Mutex to guarantee only one process will run at a time.
by Anonymous Monk on Feb 08, 2007 at 23:43 UTC
    Without looking at the Win32 API and its dark magic, I think both examples contain the same race condition between open and new. Looking at CPAN, both modules clearly state that new behaves like open when the mutex / semaphore already exists. The return value of wait should tell you which of both cases actually happened.