3,882
社区成员




/*******
Using Named Objects
The following example illustrates the use of object names by creating and opening a named mutex.
First Process
The first process uses the CreateMutex function to create the mutex object. Note that this function succeeds even if there is an existing object with the same name.
***************/
#include <windows.h>
#include <stdio.h>
#include <conio.h>
// This process creates the mutex object.
void main()
{
HANDLE hMutex;
hMutex = CreateMutex(
NULL, // default security descriptor
FALSE, // mutex not owned
TEXT("NameOfMutexObject")); // object name,这是直接写名字的,名字还可以有Gloabal\和Loacal\前缀
if (hMutex == NULL)
printf("CreateMutex error: %d\n", GetLastError() ); //这种时候,啥也不能做,只好推出了
else
if ( GetLastError() == ERROR_ALREADY_EXISTS ) //这表明 hMutex已经创建了,也就是进程已经有个实例在运行了
printf("CreateMutex opened an existing mutex\n"); // 你的程序,这这时候退出,就可以了,注意随手CloseHandle
else printf("CreateMutex created a new mutex.\n");//否则,这是第一个实例,下面就可以开工干活了
//........... 开工干活,MFC可以写在WinAPP 的派生类的构造函数中
// Keep this process around until the second process is run
_getch();
}
/***************
Second Process
The second process uses the OpenMutex function to open a handle to the existing mutex. This function fails if a mutex object with the specified name does not exist. The access parameter requests full access to the mutex object, which is necessary for the handle to be used in any of the wait functions.
#include <windows.h>
#include <stdio.h>
// This process opens a handle to a mutex created by another process.
*****************/
void main()
{
HANDLE hMutex;
hMutex = OpenMutex(
MUTEX_ALL_ACCESS, // request full access
FALSE, // handle not inheritable
TEXT("NameOfMutexObject")); // object name
if (hMutex == NULL)
printf("OpenMutex error: %d\n", GetLastError() );
else printf("OpenMutex successfully opened the mutex.\n");
}