1

I want to receive data on named pipe asynchronously. Following is my server code:

bool bContinue = true;
bool bMessageReceived = false;
int iMessage;
DWORD dwBytesRead = 0;
OVERLAPPED oReadOverlapped = {0};
oReadOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

while(bContinue)
{
    int result = ReadFile(hPipe, &iMessage, sizeof(int), NULL, &oReadOverlapped);
    int dwError = GetLastError();
    cout<< "readFile Error: " << dwError <<endl; 
    if( result )
        bMessageReceived = true;
    else
    {
       bool ret = GetOverlappedResult(hPipe, &oReadOverlapped, &dwBytesRead,                    
                     FALSE); 
       if( ret )
       {
           bMessageReceived = true;
       }
       else
       {
        dwError = GetLastError();
        cout<< "GetOverlappedResult Error: "<<dwError <<endl;
        bMessageReceived = !( !ret && dwError == ERROR_IO_INCOMPLETE);
       }
   }

   if( bMessageReceived )
   {
       ResetEvent(oReadOverlapped.hEvent);
       ProcessMessage(iMessage, hPipe);
   }

   bContinue = !IsServerStopped();
 }

Client code send message 'synchronously' with success. But every time server call readFile it returns with ERROR_IO_PENDING and GetOverlappedResult returns with ERROR_IO_INCOMPLETE. It continues in loop. I am using windows vista and Visual Stdio 2010. what could be the problem with this code.

Regards, Khurram.

user2731777
  • 171
  • 2
  • 11
  • You're not waiting for the operation to complete anywhere. Since your code doesn't do multiple I/O operations at the same time (or at least not on purpose) and doesn't do anything else while the I/O operation is running, why are you trying to use asynchronous I/O? – Harry Johnston Oct 08 '13 at 20:22
  • The only reason for doing asynchronous I/O is to check (in IsServerStopped()), if this thread has to be stopped. If I use ReadFile() synchronously and the thread is stopped or client discconect then how do i gracefully exit from thread after clean up? – user2731777 Oct 08 '13 at 22:48
  • 1
    If you choose to use synchronous IO, you can use the `CancelSynchronousIo` function if the thread has to be stopped cleanly. If you choose to use asynchronous IO, you should create an event which you can set when the thread has to be stopped cleanly. The thread can then use `WaitForMultipleObjects` to wait until either the IO finishes or the thread needs to be stopped. – Harry Johnston Oct 09 '13 at 01:37
  • possible duplicate of [Writing synchronously to a file opened with FILE\_FLAG\_OVERLAPPED](http://stackoverflow.com/questions/6663600/writing-synchronously-to-a-file-opened-with-file-flag-overlapped) – Harry Johnston Mar 31 '15 at 00:21

0 Answers0