Solved

Waitforsingleobject always results in a timeout !!!

Posted on 2004-08-03
3
1,867 Views
Last Modified: 2013-11-20
My waitforsingleobject always results in a timeout and i am unable to figure out why.. Please look at my code below..
i have a read file call .that gets called as soon as i receive a character in the input buffer. Hence i am waiting on waitcommevent and when a character appears, i issue a readfile to read all the characters that have come through my serial port.. However, waitcommevent is a blocking call. I had to make the waitcommevent timeout.. Hence, i moved to overlapped IO. But now..my waitcommevent always timeouts even though i know that there are characters to read. Please let me know what is wrong with my code..
/*********************************************************************************************/
int ReadProc1(char *str)
{
      
      /*
      Using the EV_RXCHAR flag will notify the thread that a byte arrived at the port. This event,
      used in combination with the ReadFile function, enables a program to read data only after
      it is in the receive buffer, as opposed to issuing a read that waits for the data to arrive*/


      DWORD dwCommEvent; //a variable that receives a mask indicating the type of event that occurred
      char chRead;            // Character read every time a read takes place.
      DWORD dwRead =0,Err,Bytes;            //Pointer to the variable that receives the number of bytes read
      char * str =calloc(100,sizeof(char));
      unsigned int i=0,j=2;
      BOOL fWaitingOnRead = FALSE,Ok= FALSE;

      OVERLAPPED osReader= {0};

      

      FillMemory(str, strlen(str), 0);
      //if((strcmp(p->PType,"13") == 0) && (strcmp(p->Data,"0") != 0)) stop = 0x06;
      if (stop == 0x06) terminate=1;
      if (stop == 0x03) terminate=0;
      
      
      memset(&osReader,0,sizeof(OVERLAPPED));
      osReader.hEvent = CreateEvent(
    NULL,   // no security attributes
    TRUE,  // auto reset event
    FALSE,  // not signaled
    NULL    // no name
    );
      if (osReader.hEvent == NULL)
      {
            LogEvent(hComm,"Error creating overlapped event");
      }

      for ( ; ; ) {
            if (!fWaitingOnRead)
            {

                  if (!(WaitCommEvent(hComm, &dwCommEvent,&osReader)))
                  {

                        if (GetLastError() != ERROR_IO_PENDING)
                        {
                              LogEvent (ghwnd," Error in Wait Comm Event");
                              return FALSE;
                        }
                        else
                        {
                              fWaitingOnRead = TRUE;
                              Err = WaitForSingleObject(hComm, READ_TIMEOUT);
                              
                              switch(Err)
                              {
                              case WAIT_TIMEOUT:
                                    LogEvent(ghwnd,"Timed out waiting for response from device.. check connections/power");
                                    return FALSE;
                                    break;


                              case WAIT_OBJECT_0:
                               // Event triggered. Check the status.
                                    
                                    Ok = GetOverlappedResult(hComm, &osReader, &Bytes, TRUE);
                                    if (Ok)
                                    {
                       
                                          do
                                          {
                                                                   
                                                if (ReadFile(hComm, &chRead, 1, &dwRead, NULL))
                                                {
                                          
                                                      // A byte has been read; process it.
                                                      str[i++]=chRead;
                                                                                                      }
                                                else
                                                {
                                                // An error occurred in the ReadFile call.
                                                      LogEvent(ghwnd," Read Failed With Error Code ");
                                                      break;
                                                }
                              
                                          } while (dwRead );
                                    }
                                    else
                                    {
                                          LogEvent(ghwnd,"Get Overlapped Result Failed ");
                                          return FALSE;
                                    }
                                    break;
                              default:

                                    LogEvent (ghwnd," Error in wait for single object");
                                    return FALSE;
                                    break;
                              }//End of Switch
                        }//End of GetLastError
                  }
                  else
                  {
                        LogEvent(ghwnd,"Read Completed Immedialtely");
                           /* So Proceed to readfile
                        do
                        
                        {
               
                              if (ReadFile(hComm, &chRead, 1, &dwRead, NULL))
                              {
                              
                                    // A byte has been read; process it.
                                    str[i++]=chRead;
                                    if(terminate ==1 && stop == 0x03) terminate += 1;
                                    if (chRead == stop )
                                    {
                                          terminate +=1;
                                    }
                              }
                              else
                              {
                                    // An error occurred in the ReadFile call.
                                    LogEvent(ghwnd," Read Failed With Error Code ");
                                    break;
                              }
                        
                        } while (dwRead );*/
                  }//End of Wait Comm Event
            }// End of Waiting on Read
            
      
      }

            
      }
      
 
/*********************************************************************************************
0
Comment
Question by:shubha_mohan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 48

Expert Comment

by:AlexFM
ID: 11704926
WaitCommEvent may return TRUE, in this case you can call ReadFile without waiting for overlapped event. Only if WaitCommEvent returns FALSE and GetLastError is ERROR_IO_PENDING, you need WaitForSingleObject.
WaitForSingleObject must wait for osReader.hEvent and not for hComm - this is your mistake.
There is not need in GetOverlappedResult - call ReadFile after successfull WaitForSingleObject.
0
 

Author Comment

by:shubha_mohan
ID: 11705575
Wow cool.. Thanks for locating my error !!! I still have anotehr doubt though.. Now.. that i have started using overlapped IO, can i not make any readfile /writefile calls that can be passed NULL instead of the OVERLAPPED object ?? Like in the above code, when my waitcommevent returns, i know that there is data to be read. i just want to gointo a loop reading off data till there is no more data to read.. However , a normal readfile call just returns an error (87 - ie parameter invalid") !! :(( Now .. is there any way i can overcome this problem ??
In simple words, i have an application where some calls need to be overlapped and some non overlapped . Is this possible at all ??
0
 
LVL 48

Accepted Solution

by:
AlexFM earned 250 total points
ID: 11706362
If you open COM port in overlapped mode, all calls to it should be overlapped as well. ReadFile call should have the same structure as WaitCommEvent call, plus using GetOverlappedResult:
- call ReadFile in overlapped mode.
- if returns TRUE, extract data immidiately.
- if returns FALSE and GetLastError is ERROR_IO_PENDING, call WaitForSingleObject, waiting for overlapped event.
- after succeessful execution of WaitForSingleObject call GetOverlappedResult to extract data.

From MSDN topic CreateFile:
FILE_FLAG_OVERLAPPED
When you specify FILE_FLAG_OVERLAPPED, the file read and write functions must specify an OVERLAPPED structure. That is, when FILE_FLAG_OVERLAPPED is specified, an application must perform overlapped reading and writing.

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Displaying information on the statusbar.   Continuing from the third article about sudoku.   Open the project in visual studio. Status bar – let’s display the timestamp there.  We need to get the timestamp from the document s…
Introduction: Database storage, where is the exe actually on the disc? Playing a game selected randomly (how to generate random numbers).  Error trapping with try..catch to help the code run even if something goes wrong. Continuing from the seve…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question