How to check if a HANDLE is valid or not?

losingsleeep picture losingsleeep · Apr 9, 2011 · Viewed 54k times · Source

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.

Answer

janm picture janm · Apr 9, 2011

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:

  1. Handle is opened, actual value is 0x1234
  2. Handle is used and the value is passed around
  3. Handle is closed.
  4. Some other part of the program opens a file, gets handle value 0x1234
  5. The original handle value is "checked for validity", and passes.
  6. The handle is used, operating on the wrong file.

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.