명명된 개체 사용

다음 예제에서는 명명된 뮤텍스를 만들고 열어 개체 이름을 사용하는 것을 보여 줍니다.

첫 번째 프로세스

첫 번째 프로세스는 CreateMutex 함수를 사용하여 뮤텍스 개체를 만듭니다. 이름이 같은 기존 개체가 있더라도 이 함수는 성공합니다.

#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;
}

두 번째 프로세스

두 번째 프로세스는 OpenMutex 함수를 사용하여 기존 뮤텍스에 대한 핸들을 엽니다. 지정된 이름의 뮤텍스 개체가 없으면 이 함수가 실패합니다. access 매개 변수는 모든 대기 함수에서 핸들을 사용하는 데 필요한 뮤텍스 개체에 대한 모든 액세스를 요청합니다.

#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;
}

개체 이름

뮤텍스 개체 사용