0

我正在疯狂地思考如何使用 C++ 向 Windows 上的外部 .exe 发送信号。一个人“user1764961”建议使用 Mutex,但我不太明白它是如何工作的!我也在阅读这个页面:http ://www.tutorialspoint.com/cplusplus/cpp_signal_handling.htm 但我不明白......

例如:我想向“无窗口”.exe 发送关闭信号 如果需要详细信息,我知道有关 .exe 的所有信息。

4

1 回答 1

3

尝试这个。既不是最优雅也不是最安全(非常非常不安全),而是解决问题的最简单方法。

在要关闭的应用程序中执行以下操作:

DWORD dwProcessID;
HANDLE hProcess, hMutex;
hProcess = GetCurrentProcess();
DuplicateHandle(hProcess, hProcess, hProcess, &hProcess, NULL, TRUE, DUPLICATE_SAME_ACCESS);
// write retrieved handle somewhere in file. let it be "C:\sample.txt"
// ...
hMutex = CreateMutex(NULL, TRUE, L"Look at me! I'm a scarry MUTEX");
//... Your code
// go close your video streams or do whatever you want
// ...
ReleaseMutex(hMutex);

在您的应用中:

// so now the distant proc works and you now it
// it is time to terminate it.
HANDLE hMutex, hProcess;
// read hProcess from "C:\sample.txt" 
hMutex = OpenMutex(SYNCHRONIZE, FALSE, L"Look at me! I'm scary MUTEX");
WaitForSingleObject(hMutex, INFINITE); //if your "video app" will not release the mutex you will wait forever.
TerminateProcess(hProcess, 0); //that's what you need

互斥锁是一个核心对象。您可以将其视为所有者操纵的交通信号灯。行人若想活着上路,就必须服从。

在给定的示例中,有 2 个未解决的问题。

首先是你不应该在文件中写进程句柄。那么如何获取进程句柄呢?好吧,看这里

其次,正如我之前所说,除非你是上帝,否则你不能永远等待。确保您的进程将释放 mutex 或 set WaitForSingleObject(hMutex, TIME_INTERVAL)。TIME_INTERVAL 是 DWORD。选择它就行了。

希望我的回答对你有所帮助。

于 2013-06-03T14:36:06.607 回答