开发者

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. F开发者_开发技巧irst 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?


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.


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


You have to mention UNIQUE mutex name both process in CreateMutex and in OpenMutex .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜