Is it safe to "double close" a descriptor with CloseHandle?

What are the consequences of calling CloseHandle more than once?

The docs say β€œyou shouldn't,” but I think I have a realistic case with named pipes where the handle can be closed externally (see end of post).

CloseHandle throws an exception in debug mode in this case, which tells me that the developers consider this to be serious, but the documents are not entirely clear.

(Polite request: please avoid the answer β€œjust don’t!” :-). Of course, you should avoid closing the handke more than once, and of course there are good methods to help with this: I'm just interested in what happens if you don't).

I heard that some people suggest that if the descriptor were quickly reused by the OS, you could finish closing another, different descriptor.

Is it possible?

How does Windows select handle identifiers?

Is there any guarantee that the descriptor value will be used regularly?

(for example, TCP ensures that the port number cannot be reused during a specific time frame).

Can you close the pens by type of pens? For example, can I think that I am closing the handset, but am ending the event closing?

Thanks!

John

(Context to this: I use named pipes in the client / server model. It is very difficult for me to guarantee that exactly one side is guaranteed to close the descriptor, for example, in the event of a crash / kill. Maybe I’m wrong, but, of course, the MSDN code example, seems to allow the client to close the common descriptor, and then when the server tries to close it, it is already closed).

+6
winapi
source share
3 answers

Just check:

HANDLE h = 0; h = CreateMutex(NULL, TRUE, NULL); printf("%X\n", h); CloseHandle(h); h = 0; h = CreateMutex(NULL, TRUE, NULL); printf("%X\n", h); 

In my WinXP x64, this produced:

 2E8 2E8 

So you have it.
Unlike TCP ports, descriptors are returned immediately.

Repeat this experiment with your favorite API or any combination of it.

+11
source share

You probably have the wrong pipe image. It has two ends, each of which is represented by a different handle. Yes, CloseHandle needs to be called twice to remove the channel instance. But since they are different pens, this will never cause any problems. Also note that handle instances are process dependent. Even if they have the same meaning in both processes, they do not refer to the same endpoint of the pipeline.

+4
source share

There are two things that can happen:

  • You close the handle opened by other code. This probably won't affect your code, but it could be disastrous for other code.
  • If you are working with a debugger application, you crash the application because the OS will throw an exception if it detects that an invalid handle is being closed.

None of them are particularly attractive IMHO.

+1
source share

All Articles