WriteFile hangs application when using WaitCommEvent

I am involved in problems with win32 programming communicating over a serial port using an event-based approach. I have a communication handle created as:

hComm = CreateFile(lpszCommName, GENERIC_READ | GENERIC_WRITE, 0,
    NULL, OPEN_EXISTING, 0, NULL);

and I set CommTimeouts as:

    commTimeout.ReadIntervalTimeout = MAXWORD;
    commTimeout.ReadTotalTimeoutConstant = 0;
    commTimeout.ReadTotalTimeoutMultiplier = 0;
    commTimeout.WriteTotalTimeoutConstant = 0;
    commTimeout.WriteTotalTimeoutMultiplier = 0;

I created a thread for ReadFile that looks like this:

SetCommMask(hComm, EV_RXCHAR);
while (isConnected)
{
    if (WaitCommEvent(hComm, &dwEvent, NULL)) //If i comment out this block my write file will work fine
    {
        ClearCommError(hComm, &dwError, &cs);
        if ((dwEvent & EV_RXCHAR) && cs.cbInQue)
        {
            if (!ReadFile(hComm, str, cs.cbInQue, &read_byte, NULL))
              /* Process error*/
            else if (read_byte)
                /* Print to screen */
        }
        else {
            /* Process error*/
        }
    }
}
PurgeComm(hComm, PURGE_RXCLEAR);

My Wrifile goes into WndProc, which sends characters to the communication device when WM_CHAR starts:

    VOID Write_To_Serial(WPARAM wParam, HWND hwnd){
        DWORD write_byte;
        char    str[10];
        sprintf_s(str, "%c", (char)wParam);         //Convert wParam to a string
        WriteFile(hComm, str, strlen(str), &write_byte, NULL)//Program hangs here
    }   

My problem is every time WriteFile () is called by my application and I need to get it to close it. And if I comment on WaitCommEvent () in my read stream, it works fine, but I cannot read. All pointers will be appreciated. thanks

+4
1

-.

Serial Communications MSDN (https://msdn.microsoft.com/en-us/library/ff802693.aspx),

. - , API . , , ReadFile return, , WriteFile, .

WriteFile , WaitCommEvent .

WaitCommEvent (, API CancelIoEx), WriteFile.

 VOID Write_To_Serial(WPARAM wParam, HWND hwnd){
        DWORD write_byte;
        char    str[10];
        sprintf_s(str, "%c", (char)wParam);         //Convert wParam to a string
        CancelIoEx(hComm, NULL);
        WriteFile(hComm, str, strlen(str), &write_byte, NULL);//Program hangs here
    }  

WaitCommEvent FALSE . , , WaitCommEvent, .

, , ReadFile, WaitCommEvent, WndProc WriteFile. , . , , WaitCommEvent FALSE, .

-1

Source: https://habr.com/ru/post/1610363/


All Articles