Reopening serial port fails if not closed properly with CloseHandle

后端 未结 6 996
情话喂你
情话喂你 2021-01-03 12:06

I am working with USB device on Windows that is seen as a virtual serial port. I can communicate with the device using CreateFile and ReadFile functions, but in some cases m

6条回答
  •  不知归路
    2021-01-03 12:30

    Maybe you can add a Try catch close around your main code, and call CloseHandle in the catch close. Then even if the program craches, CloseHandle will be called.

    try
    {
       HANDLE hPort = NULL;
       hPort = CreateFile(...);
       // You code...
    
    }
    catch (...)
    {
       if (hPort != NULL)
           CloseHandle(hPort);
    }
    

提交回复
热议问题