winapiprocessmultithreadingmutexsingle-instance

Win32: How to get the process/thread that owns a mutex?


I'm working an application of which only one instance must exist at any given time. There are several possibilities to accomplish this:

The mutex option seems to me the most reliable and elegant.

However, before my second instance terminates, I want to post a message to the already running instance. For this, I need a handle to the thread (or the process) that owns the mutex.

However, there seems to be no API function to get the creator/owner of a given mutex. Am I just overlooking it? Is there another way to get to this thread/process? Is there another way to go about this?

Update: This guy simply broadcast a message to all running processes. I guess that's possible, but I don't really like it...


Solution

  • I don't think there is a trivial way to resolve the actual owner of a Mutex, but the process that owns it can create other secondary items whose lifetimes are tied to it. There are plenty of mechanisms that are suitable for calling back across-process without having a main window.

    1. Register an object in the COM Running Object Table. Clients that are unable to take ownership of the Mutex can lookup the owner via the ROT and call back to the owner. A File Moniker should be suitable for registration here.
    2. Create a chunk of shared memory containing location details for the owner process. From there, write into the buffer the process handle and thread handle of a thread that can receive windows messages, and then use PostThreadMessage() to send a notification. Any other competing process may open the shared memory for read-only to determine where to send a windows message.
    3. Listen in the owner process on a Socket or Named Pipe. Probably overkill and not a good match for your needs.
    4. Use a shared file with locking. I'm not fond of this because the owner will need to poll, and it won't gracefully handle N potential other processes that could be trying to contact the owner at the same time.

    Here are reference links for the first two options.

    1. IRunningObjectTable @ MSDN , File Monikers @ MSDN
    2. Creating Named Shared Memory @ MSDN