Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Using CreateMutex to detect multiple instances

1 view
Skip to first unread message

Tom Allebrandi

unread,
Feb 7, 2000, 3:00:00 AM2/7/00
to
Hi!

I've generally used a code pattern like the following to detect whether or
not an instance of my application is already running:

char szMutexName[] = "ProgramName Instance Mutex";
HANDLE mutex = NULL;

/*
* Attempt to create the instance mutex to identify that we are here
*/
if ((mutex=CreateMutex(NULL,TRUE,szMutexName)) == NULL)
{
/*
* Failed to create the instance mutex, do something here
*/
}

/*
* Are we the first instance, or are we already running?
*/
if (GetLastError() != ERROR_ALREADY_EXISTS)
{
/*
* First instance
*
* Here, do whatever initialization is required
* (including window creation)
*/

/*
* We are initialized... release the mutex to unblock other
* instances
*/
ReleaseMutex(mutex);
}
else
{
/*
* Already running
*
* The other instance may still be initializing. Don't proceed
* until we can gain ownership of the mutex.
*/
WaitForSingleObject(mutex,INFINITE);

/*
* Now that we have the mutex, and we know that another instance
* is running and initialized, it should be safe to FindWindow()
* and SendMessage() to the other instance (assuming that the
* other instance created the main window before releasing the
* ownership of the mutex.)
*
* Here, do whatever stuuf extra instances need to do
*/

/*
* We are initialized... release the mutex to unblock other
* instances
*/
ReleaseMutex(mutex);
}

I was reading an article the other day where the author didn't seem to like
this approach. He likes creating the mutex, but doesn't use the ownership
to determine when the second instance can proceed.

http://www.pgh.net/~newcomer/nomultiples.htm

As near as I can tell, his concern comes from the following statement in
the CreateMutex() documentation:

Two or more processes can call CreateMutex to create the same named
mutex. The first process actually creates the mutex, and subsequent
processes open a handle to the existing mutex. This enables
multiple processes to get handles of the same mutex, while
relieving the user of the responsibility of ensuring that the
creating process is started first. When using this technique, you
should set the bInitialOwner flag to FALSE; otherwise, it can be
difficult to be certain which process has initial ownership.

I'm not sure what the documentation is trying to say here, specifically:
the last sentence. I thought that using the bInitialOwner to synchronize
the later instances was a key part of the method I use above.

It feels to me that the documentation is wrong, that instance of FALSE it
should say TRUE in the last sentence.

Can anyone shed some light on this?

Thanks!

--- Tom
Tom Allebrandi (t...@ytram.com)
TA Software Systems
Charlottesville, VA, USA

0 new messages