16,548
社区成员




我现有进程AB,用互斥互相监视(如果其中一个不存在的话另一个也终止)
A:
1、OnInitDialog
// TODO: Add extra initialization here
HANDLE hMutex = CreateMutex(NULL, FALSE, "B1");
SetTimer(1,2000,NULL);
2、Ontimer()
if(nIDEvent ==1)
{
HANDLE m_hMutexB2 = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "B2");
if (m_hMutexB2 == NULL)
{
// 如果已有互斥量存在则释放句柄并复位互斥量
KillTimer(1);
EndDialog(IDOK);
return;
}
}
B:
1、OnInitDialog
HANDLE hMutex = CreateMutex(NULL, FALSE, "B2");
SetTimer(1,2000,NULL);
2、Ontimer()
if(nIDEvent ==1)
{
HANDLE m_hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "B1");
if (m_hMutex == NULL)
{
// 如果已有互斥量存在则释放句柄并复位互斥量
KillTimer(1);
EndDialog(IDOK);
return;
}
}
可AB任意一个退出另一个照样运行,我看了许久逻辑上应该没错误呀!
if(1 == nIDEvent)
{
HANDLE hMutexB1 = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "B1");
if (hMutexB1)
::CloseHandle(hMutexB1);
else
{
KillTimer(1);
EndDialog(IDOK);
}
}
int WINAPI WinMain(HINSTANCE hinstExe, HINSTANCE,
PSTR pszCmdLine, int nCmdShow)
{
HANDLE h = CreateMutex(NULL, FALSE,
"{FA531CC1-0497-11d3-A180-00105A276C3E}");
lf (GetLastError() == ERROR_ALREADY_EXISTS)
{
//There is already an instance
//of the application running
return(0),
}
//This is the first instance of this application running.
//Before exiting ,close the object.
CloseHandle(h),
return(0);
}