8

Why does

HANDLE mutexHandle = INVALID_HANDLE_VALUE;
WaitForSingleObject(mutexHandle, INFINITE);

block? It does not return with an error message. Checking the handle for INVALID_HANDLE would be stupid for a mutex as I would need a mutex for accessing the mutex handle...

BTW: It does return with WAIT_FAILED if the handle was closed.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103

1 Answers1

19

From http://blogs.msdn.com/oldnewthing/archive/2004/03/02/82639.aspx:

Fourth, you have to be particularly careful with the INVALID_HANDLE_VALUE value: By coincidence, the value INVALID_HANDLE_VALUE happens to be numerically equal to the pseudohandle returned by GetCurrentProcess(). Many kernel functions accept pseudohandles, so if if you mess up and accidentally call, say, WaitForSingleObject on a failed INVALID_HANDLE_VALUE handle, you will actually end up waiting on your own process. This wait will, of course, never complete, because a process is signalled when it exits, so you ended up waiting for yourself.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 1
    I think I feel sick now... So I need to keep the old handle around and signal validity with a separate flag. Why doesn't the documentation say so... – EricSchaefer Sep 24 '09 at 13:38
  • 3
    I'd wrap `WaitForSingleObject` and return `WAIT_FAILED` for `INVALID_HANDLE_VALUE`, it will probably take less coding. – Cat Plus Plus Sep 24 '09 at 13:44