最近在捣鼓一个监控的程序,因为一个程序不明原因时常无故自动退出,时间不定。用了CreateMutex,查了一些资料,虽然还没完全懂得,也蹒跚而行,一步一步来! 以下是修修改改的代码: const int PATHSIZE = 1024; char path[PATHSIZE]; memset(path, 0, PATHSIZE); if (!GetModuleFileName(NULL,path,PATHSIZE)) { Debug("GetModuleFileName false!"); exit(0); } PathRemoveFileSpec(path); strcat(path, "//RBpro.exe"); UINT t = WinExec(path, SW_SHOW); //启动RBproMonitor,由其启动RBpro,此处是无互斥的启动进程。 if (t<32) { Debug("WinExec false, return=%d filename=%s", t, path); } bool k = true; int i = 0; while(true) //监控循环主体。 { HANDLE hMutex = CreateMutex(NULL, FALSE, "RBproMonitor"); //TRUE代表主线程拥有互斥对象 但是主线程没有释放该对象 互斥对象谁拥有 谁释放 //FLASE代表当前没有线程拥有这个互斥对象 if( GetLastError() == ERROR_ALREADY_EXISTS ) { CloseHandle(hMutex); hMutex = NULL; } else { CloseHandle(hMutex); hMutex = NULL; if(k) { UINT t = WinExec(path, SW_SHOW); //此处k=true启动,为while(true)循环体内的首次互斥,相当于启动一次互斥(RBproMonitor)的RBpro进程。 if (t<32) { Debug("WinExec false, return=%d filename=%s", t, path); } k = false; i = 0; } else //k=false不启动 { if (i==1) { Debug("RBproMonitor Wait For reset!"); } } } HANDLE hMutex1 = CreateMutex(NULL, FALSE, "RBproMonitor_Kill"); //此处为while(true)循环体内的第二次互斥。本应用中,没有进程使用该互斥信号(RBproMonitor_Kill),故此循环一直进行。 if( GetLastError() == ERROR_ALREADY_EXISTS ) { CloseHandle(hMutex1); hMutex1 = NULL; exit(0); } else if (hMutex1==NULL) { exit(0); } else { CloseHandle(hMutex1); hMutex1 = NULL; } if (i==60) { k = true; i = 0; // Sleep(x) * MAX(i) ms } Sleep(1000); i++; } 对于CreateMutex的理解,进了一步!