WaitForSingleObject和mailslot IPC

时间:2014-01-16 01:56:36

标签: winapi visual-studio-2008

我有两个程序:MailSlot_server和Mailslot_client。

Mailslot_server从此邮件槽创建邮件槽并读取消息。 Mailslot_client随时将消息写入邮件槽。

现在,在Mailslot_server程序中,我必须使用一个线程来从邮件槽中读取消息。 这是由线程执行的功能。

while (TRUE)
{
    DWORD msgSize = 0;

    Sleep(1000);
    result = GetMailslotInfo(hSlot, 0, &msgSize, 0, 0);

    if (result == FALSE)
    {
        printf("GetMailslotInfo failed with error %d\n", GetLastError());
        continue;
    }

    if (msgSize != (DWORD)MAILSLOT_NO_MESSAGE)
    {
        char buffer[1024] = {0};
        DWORD numRead = 0;

        result = ReadFile(hSlot, buffer, msgSize, &numRead, 0);
        if (!result) 
        {
            printf("ReadFile error: %d\n", GetLastError());
        }
        else if (msgSize != numRead) 
        {
            printf("ReadFile did not read the correct number of bytes!");
        }
        else
        {
                            // do something
        }
    }
}

我不需要使用Sleep()函数。你有什么建议吗?我可以使用WaitForSingleObject()函数来了解mailslot何时有消息。

1 个答案:

答案 0 :(得分:0)

是的,你可以。您需要在服务器中使用CreateEvent创建命名事件,然后在客户端中使用OpenEvent来获取它的句柄。

所以,在服务器中:

// create an auto-reset event
m_hEvent = CreateEvent(NULL, FALSE, FALSE, _T("SomeUniqueName"));

// ... when you have written a mailslot message ...
SetEvent(m_hEvent);

// on shut down
CloseHandle(m_hEvent);

在客户端:

// get a handle to the server's event
m_hEvent = OpenEvent(SYNCHRONIZE, FALSE, _T("SomeUniqueName"));

// main loop
while (/* not time to exit */)
{
    // wait for signal
    WaitForSingleObject(m_hEvent, INFINITE);

    // ... read from mailslot ....
}

您需要添加一些错误检查,并确保关闭所有打开的句柄。此外,您可能需要在客户端内进行第二个事件,以便您可以发信号通知线程整齐关闭(尽管您也可以从客户端的主线程中SetEvent强制它绕循环)。