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.
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.