#include "pch.h" #include <iostream> #include <Windows.h> //线程同步:消息、事件、临界区(不是内核对象)、互斥体 //创建互斥体对象,守护程序利用OpenMutex()函数检测对方的互斥体对象是否存在,不存在则创建进程 //线程回调函数 //参数:程序名称 DWORD WINAPI ThreadCheckProc(LPVOID lParam) { STARTUPINFOA si = { sizeof(si) }; PROCESS_INFORMATION pi = { 0 }; HANDLE hMutex; while (true) { hMutex = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, (LPCSTR)lParam); if (!hMutex) { //unicode下,用W版会失败 CreateProcessA( (LPCSTR)lParam, NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { CloseHandle(hMutex); } Sleep(500); } } int main() { DWORD Tid; //创建自己的互斥体对象 CreateMutexA(NULL, TRUE, (LPCSTR)"p1.exe"); //创建线程检测对方的互斥体 CreateThread(NULL, 0, ThreadCheckProc, (LPVOID*)"p2.exe", 0, &Tid); while (1) { Sleep(500); }; return 0; }
#include "pch.h" #include <iostream> #include <Windows.h> /线程回调函数 //参数:程序名称 DWORD WINAPI ThreadCheckProc(LPVOID lParam) { STARTUPINFOA si = { sizeof(si) }; PROCESS_INFORMATION pi = { 0 }; HANDLE hMutex; while (true) { hMutex = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, (LPCSTR)lParam); if (!hMutex) { //unicode下,用W版会失败 CreateProcessA( (LPCSTR)lParam, NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { CloseHandle(hMutex); } Sleep(500); } } int main() { DWORD Tid; //创建自己的互斥体对象 CreateMutexA(NULL, TRUE, (LPCSTR)"p2.exe"); //创建线程检测对方的互斥体 CreateThread(NULL, 0, ThreadCheckProc, (LPVOID*)"p1.exe", 0, &Tid); while (1) { Sleep(500); }; return 0; }
编译环境:vs2017 unicode
修改生成的程序为p1.exe,p2.exe,并且p1.exe,p2.exe在同一路径下,可以实现简单的双进程守护。
挂起其中的一个进程,可以实现全部关闭。或者,迅速关闭p1.exe,p2.exe亦可。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。