函数原型:
HANDLE CreateMutex(
LPSECURITY_ATTRIBUTES lpMutexAttributes,//必须为NULL
BOOL bInitialOwner, //表示mutex的范围是本线程还是全系统
LPCTSTR lpName //互斥量的名字
);
bool checkMyselfExist()//如果程序已经有一个在运行,则返回true
{
HANDLE hMutex = CreateMutex(NULL, FALSE, L"DevState");
if (hMutex && (GetLastError() == ERROR_ALREADY_EXISTS))
{
CloseHandle(hMutex);
hMutex = NULL;
return true;
}
else{
return false;
}
}
int main()
{
if (checkMyselfExist()){
cout << "program has been runnin" << endl;
}
else{
cout << "start running" << endl;
}
system("pause");
return 0;
}

本文介绍了一个简单的C++程序,通过Windows API函数CreateMutex实现互斥机制,以此来判断当前程序是否已经是运行实例,从而避免同一程序被多次启动。
2724

被折叠的 条评论
为什么被折叠?



