Under the WIN32, there are many ways to implement mutual exclusion of programs, I simply analyze the following different implementations:
The realization under the VC
Visual C + + is the most important and powerful programming tool for WIN32 programming, quoting a word VC is "only you can not imagine, no VC can not do." Less nonsense, below to see how the VC is the function.
A Using the compiler to implement (using the MFC framework):
Add the following lines to the beginning of the. cpp file:#pragma data_seg("Shared")
int volatile g_lAppInstance =0;
#pragma data_seg()
Let's take a look at the contents of the above:
The first sentence #pragma data_seg ("shared") creates a new section called Shared.
The second sentence int volatile g_lappinstance =0 the g_lappinstance into the shared section. Note that only the g_lappinstance is initialized at this point, the compiler will put it into the shared section, otherwise it will be placed in a section other than shared. (In fact, the Visual C + + compiler provides a allocate specifier that allows us to put data into any section.) )
The third sentence indicates that the compiler shared section ends. In #pragma comment(linker,"/section:Shared,RWS")
this sentence, we make the compiler aware that our shared section has properties for reading, writing, and sharing. This is the key to our mutual exclusion operation. This allows us to share g_lappinstance variables between multiple instances of the application.
Add in the InitInstance () function: The if(++g_lAppInstance>1)
{
AfxMessageBox("程序已经运行!");
return FALSE;
}
above code works when the program is started on the G_LAPPINSTANCD plus 1, and if the value is found to be greater than 1, then display message Box and return false. (Note: If InitInstance returns False in MFC, the program will not be run!) )
B. Using named Mutex objects:
Using API function CreateMutex to create named mutexes to implement mutex is a more general method, we can add the following code in the Inininstance () function: HANDLE hObject = CreateMutex(NULL,FALSE,"LJPXYXC");
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hObject);
AfxMessageBox("程序已经运行!");
return FALSE;
}
The above Createmutext function creates a name called "LJPXYXC" A named mutex object that, when the second instance of the program is shipped, invokes CreateMutex to return error_already_exists. We implement the mutex operation of the program according to this value.