进程互斥(当前程序已运行!)
实现功能,当程序已经运行时,禁止另外开启一个同样的程序,这时可以使用进程互斥实现,即创建一个有名字的互斥量
在windows下:
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") //取消dos框的弹出
#include "windows.h"
#include "stdio.h"
int main()
{
HANDLE m_hMutex = CreateMutex(NULL, TRUE, "mutex_1"); //创建名称为mutex_1的互斥量
DWORD dwRet = GetLastError();
if (m_hMutex)
{
if (ERROR_ALREADY_EXISTS == dwRet)
{
MessageBox(NULL,"同样的程序已运行,不能再次运行!","warning!",MB_OK);
CloseHandle(m_hMutex);
return 0;
}
}
else
{
MessageBox(NULL, "创建互斥量错误,程序退出!", "warning!", MB_OK);
CloseHandle(m_hMutex);
return 0;
}
MessageBox(NULL, "程序运行起来了", "进程1", MB_OKCANCEL);
CloseHandle(m_hMutex);
return 0;
}
还没有评论,来说两句吧...