Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a HANDLE is valid or not?

Tags:

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.

like image 787
losingsleeep Avatar asked Apr 09 '11 07:04

losingsleeep


People also ask

How to check if handle is valid c++?

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.

Is window handle valid?

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


2 Answers

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.

like image 78
janm Avatar answered Sep 19 '22 12:09

janm


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

like image 25
Krit Avatar answered Sep 20 '22 12:09

Krit