In C++, I have opened a serial port that has a HANDLE
. Since the port may close by an external application, how can I verify that the HANDLE
is still valid before reading data?
I think it can be done by checking the HANDLE
against a suitable API function, but which?
Thank you.
You can just test the duplicated handle address value on value greater than yours handle address and if it is greater, then the handle is not treated as invalid and so is not reused.
A window handle is valid and usable in all processes that are in the same desktop. Everything started by the current user is in the same desktop. Yes, you could place the HWND in shared memory for use by multiple processes. To check if an HWND is still valid you can call IsWindow().
Checking to see whether a handle is "valid" is a mistake. You need to have a better way of dealing with this.
The problem is that once a handle has been closed, the same handle value can be generated by a new open of something different, and your test might say the handle is valid, but you are not operating on the file you think you are.
For example, consider this sequence:
So, if it is your process, you need to keep track of which handles are valid and which ones are not. If you got the handle from some other process, it will have been put into your process using DuplicateHandle(). In that case, you should manage the lifetime of the handle and the source process shouldn't do that for you. If your handles are being closed from another process, I assume that you are the one doing that, and you need to deal with the book keeping.
Some WinAPI functions return meaningless ERROR_INVALID_PARAMETER even if valid handles are passed to them, so there is a real use case to check handles for validity.
GetHandleInformation function does the job: http://msdn.microsoft.com/en-us/library/ms724329%28v=vs.85%29.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With