Win32:如何获取拥有互斥锁的进程/线程? [英] 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:
- 检查正在运行的进程中是否存在一个与我们的EXE名称匹配的文件(不可靠)
- 找到主窗口(不可靠,我并不总是有主窗口)
- 创建具有唯一名称(GUID)的互斥锁
互斥锁选项在我看来是最可靠,最优雅的.
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.
但是,似乎没有API函数可以获取给定互斥锁的创建者/所有者.我只是俯瞰它吗?还有另一种方法可以访问该线程/进程吗?还有另一种方法可以解决这个问题吗?
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...
推荐答案
我认为没有简单的方法可以解决Mutex的实际所有者,但是拥有该Mutex的过程可以创建其他使用寿命为绑定到它.有很多机制可用于在没有主窗口的情况下回调整个进程.
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.
- 在COM运行对象表中注册一个对象.无法获得Mutex所有权的客户端可以通过ROT查找所有者,然后回叫所有者. File Moniker应该适合在这里注册.
- 创建一个共享内存块,其中包含所有者进程的位置详细信息.从那里,将可以接收Windows消息的线程的进程句柄和线程句柄写入缓冲区,然后使用PostThreadMessage()发送通知.任何其他竞争过程都可以打开共享内存以进行只读操作,以确定将Windows消息发送到的位置.
- 在套接字或命名管道上监听所有者进程.可能过大了,不能很好地满足您的需求.
- 使用带锁定的共享文件.我不喜欢这样做,因为所有者需要进行轮询,并且不会优雅地处理N个可能试图同时与所有者联系的其他进程.
以下是前两个选项的参考链接.
Here are reference links for the first two options.
- IRunningObjectTable @ MSDN , File Monikers @ MSDN
- Creating Named Shared Memory @ MSDN
这篇关于Win32:如何获取拥有互斥锁的进程/线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!