Windows Thread Synchronization 18

 

 

Second Process Program Example

 

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.

Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.

 

 

 

Using Named Objects Program Examples: Mutex object - Second Process Program Example, creating new Win32 C++ empty console application project

 

Then, add the source file and give it a suitable name.

 

Using Named Objects Program Examples: Mutex object - Second Process Program Example - adding new C++ source file

 

Next, add the following source code.

 

#include <windows.h>

#include <stdio.h>

 

// This process opens a handle to a mutex created by another process

int wmain(void)

{

    HANDLE hMutex;

 

    hMutex = OpenMutex(

        MUTEX_ALL_ACCESS,            // request full access

        FALSE,                       // handle not inheritable

        LMyGedikMutex);  // object name

 

    if (hMutex == NULL)

        wprintf(LOpenMutex() failed, error %d\n, GetLastError() );

    else

            wprintf(LOpenMutex() successfully opened the mutex...\n);

 

      if(CloseHandle(hMutex) != 0)

            wprintf(LCloseHandle() is OK!\n);

      else

            wprintf(LCloseHandle() failed with error %d\n, GetLastError());

 

    return 0;

}

 

Firstly, re-run the previous program, then this program. The following screenshot is a sample output.

 

Using Named Objects Program Examples: Mutex object - Second Process Program Example - a sample console program output

 

 

 

< Thread Synchronization 17 | Thread Synchronization Programming | Win32 Programming | Thread Synchronization 19 >