Using Named Objects

The following examples illustrate the use of object names by creating and opening named objects.

Mutex

The first process uses the CreateMutex function to create the mutex object. Note that the function succeeds even if there is an existing object with the same name.

// One process creates the mutex object.

HANDLE hMutex; 
DWORD dwErr; 

hMutex = CreateMutex( 
    NULL,                  // no security descriptor
    FALSE,                 // mutex not owned
    "NameOfMutexObject");  // object name

if (hMutex == NULL) 
    printf("CreateMutex error: %d\n", GetLastError() ); 
else 
    if ( GetLastError() == ERROR_ALREADY_EXISTS ) 
        printf("CreateMutex opened existing mutex\n"); 
    else 
        printf("CreateMutex created new mutex\n"); 
 

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.

// Another process opens a handle to the existing mutex.

HANDLE hMutex; 

hMutex = OpenMutex( 
    MUTEX_ALL_ACCESS,      // request full access
    FALSE,                 // handle not inheritable
    "NameOfMutexObject");  // object name

if (hMutex == NULL) 
    printf("OpenMutex error: %d\n", GetLastError() ); 
 
Semaphore

The following example uses the CreateSemaphore function to illustrate a named-object creation operation that fails if the object already exists.

HANDLE CreateNewSemaphore(LPSECURITY_ATTRIBUTES lpsa, 
    LONG cInitial, LONG cMax, LPTSTR lpszName) 
{ 
    HANDLE hSem; 

// Create or open a named semaphore.

    hSem = CreateSemaphore( 
        lpsa,         // security attributes
        cInitial,     // initial count
        cMax,         // maximum count
        lpszName);    // semaphore name

// Close handle, and return NULL if existing semaphore opened.

    if (hSem != NULL && GetLastError() == ERROR_ALREADY_EXISTS) 
    { 
        CloseHandle(hSem); 
        return NULL; 
    }

// If new semaphore was created, return the handle.

    return hSem; 
}