Condividi tramite


Uso di oggetti denominati

L'esempio seguente illustra l'uso dei nomi degli oggetti creando e aprendo un mutex denominato.

Primo processo

Il primo processo usa la funzioneCreateMutexper creare l'oggetto mutex. Si noti che questa funzione ha esito positivo anche se è presente un oggetto esistente con lo stesso nome.

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

Secondo processo

Il secondo processo usa la funzione OpenMutexper aprire un handle al mutex esistente. Questa funzione ha esito negativo se non esiste un oggetto mutex con il nome specificato. Il parametro di accesso richiede l'accesso completo all'oggetto mutex, che è necessario affinché l'handle possa essere utilizzato in una delle funzioni di attesa.

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

nomi di oggetti

Uso di Oggetti Mutex