Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
I connect to my USB device through function
C++
HANDLE hDevice = CreateFile("\\\\.\\dev_name",
  GENERIC_READ | GENERIC_WRITE,
  0,
  NULL,
  OPEN_EXISTING,
  FILE_ATTRIBUTE_NORMAL,
  NULL);
If my usb device was suprisely removed and after that I tried CloseHandle Windows crash to BSOD. What can I do to make the handle close correctly?

What I have tried:

I tried use RegisterDeviceNotification to track device event DBT_DEVICEQUERYREMOVE, but this event does not seem to be triggered if device was suprisely removed.
Posted
Updated 27-Nov-19 20:21pm
v2
Comments
11917640 Member 27-Nov-19 10:48am    
Try DBT_DEVICEREMOVECOMPLETE.
MaxSandi 28-Nov-19 5:03am    
DBT_DEVICEREMOVECOMPLETE called after usb device was removed, and if I used CloseHandle Windows crashed.
[no name] 28-Nov-19 10:16am    
Only an idea: E.g. Process Explorer from Sysinternals shows you all the handles used by a process. So I would check with Process Explorer whether the handle disappears if the usb is removed.
If the handle disappears in Process Explorer you "only" need a way to get the list of Handles in use programatically and check whether your Handle is still in the list.
I'm aware, it's a crazy idea ;)

[Edit]
This maybe can help to get the list of handles: Listing Used Files[^]

If the USB device has been unplugged, your handle will be invalid, there is nothing to do!
I would put the CloseHandle in try/catch block and set the handle to INVALID_HANDLE if it fails.
Try something like this:

C++
HANDLE hDevice = CreateFile("\\\\.\\dev_name",
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

// Do something with it (ReadFile/WriteFile) ...

try
{
  if (hDevice != INVALID_HANDLE_VALUE)
       CloseHandle(hDevice);
}
catch(...)
{
  hDevice = INVALID_HANDLE_VALUE;
}
 
Share this answer
 
v2
Comments
MaxSandi 28-Nov-19 4:48am    
Did not work out. Anyway crash to BSOD with exceptions NO_MORE_IRP_STACK_LOCATIONS or SYSTEM_SERVICE_EXCEPTION after CloseHandle
Check that the handle is valid with GetHandleInformation. Read it for further details.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900