Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regulating IPC between two processes with mutex

I am working on a project that creates two processes and I want to regulate the IPC between them.

The processes are created with the createProces function, and I want to use a mutex to do some IPC.

In Linux I do this with semaphores, however I have read that for IPC in Windows I have to use a mutex.

In windows I can't seem to get it to work. First I create the treads like this:

CreateProcess(IpApplicationName, NULL, NULL, NULL, FALSE,   CREATE_NEW_CONSOLE, NULL, NULL,     &StartInfo, &ProcessInfo);
CreateProcess(IpApplicationName, NULL, NULL, NULL, FALSE,   CREATE_NEW_CONSOLE, NULL, NULL,     &StartInfo2, &ProcessInfo2);

The processes start up normal but when I remove the releaseMutex call from one process it won't be kept waiting in that process. Here is process one:

volatile HANDLE hMutex; // Global hMutex Object


int main()
{
     hMutex=CreateMutex(NULL,FALSE,NULL);

    while(1)
    {

        WaitForSingleObject(hMutex,INFINITE);
        printf("Thread writing to database...\n");
        Sleep(2000);
        ReleaseMutex(hMutex);
    }

    return 0;
 }

In process two I open the mutex with open mutex and comment the releaseMutex (so that it will be stuck here, for testing. However it will keep on going):

int main()
{

 while(1)
 {
    HANDLE hMutex;

    hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,MUTEXNAME);

    WaitForSingleObject(hMutex,INFINITE);
    printf("Thread writing to database22...\n");
    Sleep(2000);
    //ReleaseMutex(hMutex);
 }

    return 0;
}

Can anyone tell me what I am doing wrong?

like image 780
RSNL Avatar asked Mar 03 '26 21:03

RSNL


2 Answers

If you were checking errors on these Win32 API calls it would be obvious. The OpenMutex call must be failing, as this code is written, since nobody else has yet created a mutex with that name.

From the OpenMutex docs:

The OpenMutex function enables multiple processes to open handles of the same mutex object. The function succeeds only if some process has already created the mutex by using the CreateMutex function.

Every Win32 API can fail - you need to check for and handle those errors properly.

like image 115
Steve Townsend Avatar answered Mar 06 '26 09:03

Steve Townsend


You create anonymous Mutex using CreateMutex, then try to find it by name

like image 32
Ulterior Avatar answered Mar 06 '26 10:03

Ulterior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!