views:

81

answers:

2

I note an applications handle when I use the shell function to open it. I then use that handle to close the application later. However the user can also close that other application himself. Can that handle then be reused by windows so that when I use that handle I close a different process. If it is possible is it likely?

+2  A: 

You can wait on a process handle to figure out when it is exited.

WaitForSingleObject(hProcess, INFINITE);

Once this returns, you know the process has exited and you don't need to close it.

FigBug
No, calling CloseHandle() is required to avoid a leak.
Hans Passant
thanks for this but it seems that the handle won't be reused because it stays open until the app that did the shell command closes it.
jjb
+1  A: 

No, you don't have to worry about it. The handle returned by, say, OpenProcess, ShellExecuteEx() or CreateProcess keeps the process object alive. That's how it is possible to call GetExitCodeProcess() to retrieve the exit code after the process is terminated.

The object doesn't get released until the last handle on it is closed. Opposite of earlier advice given in this thread, it is very important that you call CloseHandle() or you'll have a leak.

Hans Passant
Thanks, but I don't quite follow. The memory leak here as a result of closehandle(), not being called. Will it be cleared up once the app that did the shell call is closed properly?
jjb
Yes, Windows cleans up handles that were not closed. Don't let it get that far.
Hans Passant
jjb