Search code examples
c++winapiuart

How to check if WriteFile function is done


I want to check if the WriteFile function is done writing to UART so that i can call ReadFile on the same ComDev without causing an Exception.

It seems the WriteFile function can return before writing is done.

BOOL WriteCommBlock(HANDLE * pComDev, char *pBuffer , int BytesToWrite)
{
while(fComPortInUse){}

fComPortInUse = 1; 

BOOL       bWriteStat   = 0;
DWORD      BytesWritten = 0;
COMSTAT    ComStat      = {0};
OVERLAPPED osWrite      = {0,0,0};

if(WriteFile(*pComDev,pBuffer,BytesToWrite,&BytesWritten,&osWrite) == FALSE)
{
    short Errorcode = GetLastError();
    if( Errorcode != ERROR_IO_PENDING )
        short breakpoint = 5; // Error

    Sleep(1000); // complete write operation TBD

    fComPortInUse = 0; 
    return (FALSE);
}


fComPortInUse = 0; 
return (TRUE);
}

I used Sleep(1000) as an workaround, but how can i wait for an appropriate time?


Solution

  • Since you didn't say that you need asynchronous I/O, you should try synchronous. It's easier. I think if you just pass a null pointer for the OVERLAPPED arg you get synchronous, blocking, I/O. Please see the example code I wrote in the "Windows C" section of this document:

    http://www.pololu.com/docs/0J40/