Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to "double-close" a handle using CloseHandle?

Tags:

winapi

handles

What are the implications of calling CloseHandle more than once?

The docs say "you shouldn't" but I think I have a realistic case with named pipes where a handle might be closed externally (See end of post).

CloseHandle throws an exception in debug mode in this case, which suggests to me the developers think this is serious, but the docs aren't exactly clear.

(Polite request: Please avoid the answer "just don't!" :-). Of course one should avoid closing a handke more than once, and of course there are good techniques to help with this: I'm just interested in what happens if you don't).

I've heard some people suggest that if the handle was quickly reused by the OS you might end up closing another, different handle.

Is this likely?

How does Windows choose handle IDs?

Is there any guarantee about how regularly a handle value will be reused?

(e.g. TCP ensures that a port number cannot be reused within a certain timeframe).

Can you close handles accross handle types? E.g., could I be thinking I'm closing a pipe but end up closing an Event?

Thanks!

John

(Context to this: I'm using named pipes in a client/server model. It seems to me very difficult to ensure that exactly one party is guaranteed to close the handle, e.g. in process crash/killed case. Perhaps I'm wrong, but certainly the MSDN sample code seems to my mind to allow the client to close the shared handle, and then when the server tries to close it, it is already closed).

like image 675
John Avatar asked Jul 05 '10 11:07

John


1 Answers

Simple enough to 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 there you have it.
Unlike TCP ports, handles are recycled immediately.

Repeat this experiment with your favorite API or any mix thereof.

like image 141
shoosh Avatar answered Nov 08 '22 09:11

shoosh