Joseph Galbraith wrote:
I actually think the code as originally written was correct. (Although if ERR() is simply a debug tracing macro, more error handling is probably needed.)
No, this way only one application can successfully load it at the same time.
Regardless of whether the mutex is newly created or pre-existing, CreateMutex() will return a handle to it.
CreateMutex fails if a named object is supposed to be created but already exists. GetLastError() then will - as you mentioned below - return ERROR_ALREADY_EXISTS or another failure code.
In the case of a pre-existing mutex, the handle to the existing object is returned.
Not by CreateMutex.
If it is important to know whether the mutex was created or not, GetLastError() can be checked in the success case for the value ERROR_ALREADY_EXISTS (which in this case is not really an error, since the function succeeded.)
The last error code won't be changed by CreateMutex if it returns success. There's only a few APIs that do that.
If CreateMutex() returns NULL, it failed for some other reason (than that the mutex already existed, since CreateMutex doesn't fail in this case.)
Quote from the PSDK: "If lpName matches the name of an existing event, semaphore, waitable timer, job, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space."
Calling OpenMutex would not be productive in this case.
It is the only possibility.
Best Regards, Thomas