Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. CloseHandle() freezes the program...

CloseHandle() freezes the program...

Scheduled Pinned Locked Moved C / C++ / MFC
jsonhelptutorialquestion
4 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Offline
    L Offline
    learningvisualc
    wrote on last edited by
    #1

    Hi all, I have made a application in which i am reading a port using CreateFile() API with FILE_FLAG_OVERLAPPED parameter as NULL. This all processing i have done in worker thread. Everything is working fine but the problem is when i am trying to close the process i am using CloseHandle API and when the control enters in CloseHandle() the program frezees and there is no option of closing it. The code i am using is as below

    void CUse::ThreadStart()
    {
    ThreadHandle = AfxBeginThread(Thread , (LPVOID) this);
    }
    UINT Thread(LPVOID pParam)
    {
    serial_handle = CreateFile(port_arg, GENERIC_READ | GENERIC_WRITE,
    0, NULL, OPEN_EXISTING,NULL,NULL);
    .
    .
    .
    .
    //Code for reading the port

    }
    void CUse::OnCancel()
    {
    ThreadHandle->SuspendThread();
    if(MessageBox("Are you sure to stop the process?","ReadingPort",MB_YESNO)==6)
    {
    ZeroMemory(rxBuffer,128);
    ZeroMemory(rxtemp,256);
    tempid=0;
    CloseHandle(serial_handle);
    CDialog::OnCancel();
    ::TerminateThread(ThreadHandle->m_hThread,0);
    }
    else
    ThreadHandle->ResumeThread();
    }

    How to resolve this problem or any alternate way of doing it... Thanks in advance

    _ I 2 Replies Last reply
    0
    • L learningvisualc

      Hi all, I have made a application in which i am reading a port using CreateFile() API with FILE_FLAG_OVERLAPPED parameter as NULL. This all processing i have done in worker thread. Everything is working fine but the problem is when i am trying to close the process i am using CloseHandle API and when the control enters in CloseHandle() the program frezees and there is no option of closing it. The code i am using is as below

      void CUse::ThreadStart()
      {
      ThreadHandle = AfxBeginThread(Thread , (LPVOID) this);
      }
      UINT Thread(LPVOID pParam)
      {
      serial_handle = CreateFile(port_arg, GENERIC_READ | GENERIC_WRITE,
      0, NULL, OPEN_EXISTING,NULL,NULL);
      .
      .
      .
      .
      //Code for reading the port

      }
      void CUse::OnCancel()
      {
      ThreadHandle->SuspendThread();
      if(MessageBox("Are you sure to stop the process?","ReadingPort",MB_YESNO)==6)
      {
      ZeroMemory(rxBuffer,128);
      ZeroMemory(rxtemp,256);
      tempid=0;
      CloseHandle(serial_handle);
      CDialog::OnCancel();
      ::TerminateThread(ThreadHandle->m_hThread,0);
      }
      else
      ThreadHandle->ResumeThread();
      }

      How to resolve this problem or any alternate way of doing it... Thanks in advance

      _ Offline
      _ Offline
      _Superman_
      wrote on last edited by
      #2

      One thing you can do here is to open the port outside the thread and then pass in the handle to the thread. I'm saying this because you're opening the port in one thread and closing it in another.

      «_Superman_»
      I love work. It gives me something to do between weekends.

      Microsoft MVP (Visual C++)

      Polymorphism in C

      1 Reply Last reply
      0
      • L learningvisualc

        Hi all, I have made a application in which i am reading a port using CreateFile() API with FILE_FLAG_OVERLAPPED parameter as NULL. This all processing i have done in worker thread. Everything is working fine but the problem is when i am trying to close the process i am using CloseHandle API and when the control enters in CloseHandle() the program frezees and there is no option of closing it. The code i am using is as below

        void CUse::ThreadStart()
        {
        ThreadHandle = AfxBeginThread(Thread , (LPVOID) this);
        }
        UINT Thread(LPVOID pParam)
        {
        serial_handle = CreateFile(port_arg, GENERIC_READ | GENERIC_WRITE,
        0, NULL, OPEN_EXISTING,NULL,NULL);
        .
        .
        .
        .
        //Code for reading the port

        }
        void CUse::OnCancel()
        {
        ThreadHandle->SuspendThread();
        if(MessageBox("Are you sure to stop the process?","ReadingPort",MB_YESNO)==6)
        {
        ZeroMemory(rxBuffer,128);
        ZeroMemory(rxtemp,256);
        tempid=0;
        CloseHandle(serial_handle);
        CDialog::OnCancel();
        ::TerminateThread(ThreadHandle->m_hThread,0);
        }
        else
        ThreadHandle->ResumeThread();
        }

        How to resolve this problem or any alternate way of doing it... Thanks in advance

        I Offline
        I Offline
        Iain Clarke Warrior Programmer
        wrote on last edited by
        #3

        You've suspended a thread with work still happening on a file handle. Then pulling the rug out from under it. Who know's what was going on in that thread? Any time I see a thread being suspended from outside, alarm bells ring. TerminateThread just made them louder. As you're already working with overlapped I/O... Why not pass your thread a handle to an Event. Then open and close the handle local to the event (this last bit is optional). Some pseudo code (ie, I don't have access to a compiler right now)

        UINT MyThread (LPVOID lpParam)
        {
        CMyContext *pSomeStruct = (CMyContext *) lpParam;
        OVERLAPPED o = {0};
        HANDLE hWait = { NULL, NULL };
        o.hEvent = hWait [0] = CreateEvent (...);
        hWait [1] = pSomeStruct->m_hQuitThreadEvent; // created outside, so our thread can be finished with SetEvent.

        while (1)
        {
            if (ReadFile (hPort,  ..., &o))
            {
               Dostuffwithdata ()
            }
            else if (GetLastError () == ERROR\_IO\_PENDING) // which will happen a lot
            {
                nWait = WaitForMultipleObjects (hWait, 2);
                if (hWait == WAIT\_OBJECT\_0) // we have data
                {
                    // grab data, and do what we like with it
                }
                else if (hWait == WAIT\_OBJECT\_0 + 1)
                {
                    // we've received a quit signal!
                    CancelIo (); // Important to clear dangling overlapped I/O
                    break;
                }
                else
               {
                   // other tidying up code
                }
            }
        }
        
        CloseHandle (o.hEvent);
        
        return nReturn;
        

        }

        You have a good amount of work to make the above fit for production, but I hope it sets you on the Right (ie, my example) path. Iain.

        I am one of "those foreigners coming over here and stealing our jobs". Yay me!

        S 1 Reply Last reply
        0
        • I Iain Clarke Warrior Programmer

          You've suspended a thread with work still happening on a file handle. Then pulling the rug out from under it. Who know's what was going on in that thread? Any time I see a thread being suspended from outside, alarm bells ring. TerminateThread just made them louder. As you're already working with overlapped I/O... Why not pass your thread a handle to an Event. Then open and close the handle local to the event (this last bit is optional). Some pseudo code (ie, I don't have access to a compiler right now)

          UINT MyThread (LPVOID lpParam)
          {
          CMyContext *pSomeStruct = (CMyContext *) lpParam;
          OVERLAPPED o = {0};
          HANDLE hWait = { NULL, NULL };
          o.hEvent = hWait [0] = CreateEvent (...);
          hWait [1] = pSomeStruct->m_hQuitThreadEvent; // created outside, so our thread can be finished with SetEvent.

          while (1)
          {
              if (ReadFile (hPort,  ..., &o))
              {
                 Dostuffwithdata ()
              }
              else if (GetLastError () == ERROR\_IO\_PENDING) // which will happen a lot
              {
                  nWait = WaitForMultipleObjects (hWait, 2);
                  if (hWait == WAIT\_OBJECT\_0) // we have data
                  {
                      // grab data, and do what we like with it
                  }
                  else if (hWait == WAIT\_OBJECT\_0 + 1)
                  {
                      // we've received a quit signal!
                      CancelIo (); // Important to clear dangling overlapped I/O
                      break;
                  }
                  else
                 {
                     // other tidying up code
                  }
              }
          }
          
          CloseHandle (o.hEvent);
          
          return nReturn;
          

          }

          You have a good amount of work to make the above fit for production, but I hope it sets you on the Right (ie, my example) path. Iain.

          I am one of "those foreigners coming over here and stealing our jobs". Yay me!

          S Offline
          S Offline
          SRIVATHSAN VIJAYA
          wrote on last edited by
          #4

          Hi, Even I face the same problem when i try to close the handle. I haven't used any thread to create or close the handle. I have literally used CreateFileW() to create a handle for serial port communication.

          hComm = CreateFileW (pcCommPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

          Where pcCommPort is "COM_2" CreateFileW call succeeds even if device is not connected. I have send few commands through WriteFile() and read ReadFile() api's and tried to close the handle using

          CloseHandle(hComm)

          But my application hangs infinitely. What would be the exact root cause for this issue? Sample:

          While(1)
          {
          i = 0;
          hComm = CreateFileW (pcCommPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
          while(i < 10)
          {
          i++;
          WriteFile(hComm , &txBuffer[0], numBytesToTx, (DWORD*)&numBytesTx, NULL);
          ReadFile(hComm , &get_data[i], 1, (DWORD*)&numBytesRx, NULL);
          }
          CloseHandle(hComm);
          hComm = NULL;
          }

          1 Reply Last reply
          0
          Reply
          • Reply as topic
          Log in to reply
          • Oldest to Newest
          • Newest to Oldest
          • Most Votes


          • Login

          • Don't have an account? Register

          • Login or register to search.
          • First post
            Last post
          0
          • Categories
          • Recent
          • Tags
          • Popular
          • World
          • Users
          • Groups