Delen via


Benoemde objecten gebruiken

In het volgende voorbeeld ziet u het gebruik van objectnamen door een benoemde mutex te maken en te openen.

Eerste proces

Het eerste proces maakt gebruik van de functie CreateMutex om het mutex-object te maken. Houd er rekening mee dat deze functie slaagt, zelfs als er een bestaand object met dezelfde naam is.

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

Tweede proces

Het tweede proces maakt gebruik van de functie OpenMutex om een ingang te openen voor de bestaande mutex. Deze functie mislukt als er geen mutex-object met de opgegeven naam bestaat. De toegangsparameter vraagt volledige toegang tot het mutex-object aan, wat nodig is voor het handvat dat in een van de wachtfuncties moet worden gebruikt.

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

objectnamen

Mutex-objecten gebruiken