Używanie nazwanych obiektów
Poniższy przykład ilustruje użycie nazw obiektów przez utworzenie i otwarcie nazwanego mutexu.
Pierwszy proces
Pierwszy proces używa funkcji CreateMutex w celu utworzenia obiektu mutex. Należy pamiętać, że ta funkcja powiedzie się, nawet jeśli istnieje obiekt o tej samej nazwie.
#include <windows.h>
#include <stdio.h>
#include <conio.h>
// This process creates the mutex object.
int main(void)
{
HANDLE hMutex;
hMutex = CreateMutex(
NULL, // default security descriptor
FALSE, // mutex not owned
TEXT("NameOfMutexObject")); // object name
if (hMutex == NULL)
printf("CreateMutex error: %d\n", GetLastError() );
else
if ( GetLastError() == ERROR_ALREADY_EXISTS )
printf("CreateMutex opened an existing mutex\n");
else printf("CreateMutex created a new mutex.\n");
// Keep this process around until the second process is run
_getch();
CloseHandle(hMutex);
return 0;
}
Drugi proces
Drugi proces używa funkcji OpenMutex, aby otworzyć dojście do istniejącego mutexu. Ta funkcja kończy się niepowodzeniem, jeśli obiekt mutex o określonej nazwie nie istnieje. Parametr dostępu żąda pełnego dostępu do obiektu mutex, co jest niezbędne, aby uchwyt był używany w dowolnej z funkcji oczekiwania.
#include <windows.h>
#include <stdio.h>
// This process opens a handle to a mutex created by another process.
int main(void)
{
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");
CloseHandle(hMutex);
return 0;
}
Tematy pokrewne