Is there a way to check if a (file) handle is valid?
Is there any way to check if a handle, in my case returned by CreateFile, is val开发者_StackOverflow中文版id?
The problem I face is that a valid file handle returned by CreateFile (it is not INVALID_HANDLE_VALUE) later causes WriteFile to fail, and GetLastError claims that it is because of an invalid handle.
Since it seems that you are not setting the handle value to INVALID_HANDLE_VALUE
after closing it, what I would do is set a read watchpoint on the HANDLE
variable, which will cause the debugger to break at each line that accesses the value of the HANDLE
. You will be able to see the order in which the variable is accessed, including when the variable is read in order to pass it to CloseHandle
.
See: Adding a watchpoint (breaking when a variable changes)
Your problem is caused most probably by either of two things:
- You may close the file handle, nevertheless you still try to use it
- File handle is overwritten due to a memory corruption
Generally it's a good practice to assign INVALID_HANDLE_VALUE
to every handle as long as it's not supposed to contain any valid handle value.
In simple words - when your variable is declared - immediately initialize it to this value. And also write this value into your variable immediately after you close the file handle.
This will give you an indication of (1) - attempt to use the file handle which is already closed (or hasn't been opened yet)
The other answers are all important for your particular problem.
However, if you are given a HANDLE
and simply want to find out whether it is indeed an open file handle (as opposed to, e.g., a handle to a mutex or a GDI object etc.), there is the Windows API function GetFileInformationByHandle for that.
Depending on the permissions your handle grants you for the file, you can also try to read some data from it using ReadFile or perform a null write operation using WriteFile with nNumberOfBytesToWrite
set to 0.
Open-File are kept as a Data Structure in kernel, I don't think that has a official way to detect a file-handle is valid, just use it and check Error code as INVALID_HANDLE. Are you sure no others thread closed that file-handle?
Checking the validity of the handle is a band-aid, at best.
You should debug the process - set a breakpoint at the point the handle is set up (file open) and when you hit that code and after the handle is set up, set a second conditional breakpoint to trigger when the handle value changes.
This should enable you to work out the underlying cause rather than just check the handle is valid on each access, which is unreliable, costly and not necessary given correct logic.
Just to add to what everyone else is saying, make sure that you check the return value when you call CreateFile
. IIRC, it will return INVALID_HANDLE_VALUE
on failure, at which point you should call GetLastError
to find out why.
精彩评论