Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure that UnhookWindowsHookEx is called even upon abnormal termination?

Unfortunately, MSDN is not clear enough with it. I'm writing a program which uses a global hook, and I'm worrying about what would happen if the program terminates abnormally (crashes, killed by user, etc).

  1. Does Windows automatically unhook global hooks installed by a process when the process terminates?

  2. If not, is it possible to call UnhookWindowsHookEx() in another process to release the hook? (I'm thinking of doing this in a hooked thread, if it detects that the installer process is dead.)

  3. If the answers were no and no, isn't it dangerous to leave a global hook active when the installer process is terminated? What are the standard methods of dealing with this situation?

  4. I've read in MSDN that UnhookWindowsHookEx() doesn't free the dll loaded in other processes, but it doesn't say when will the dll be freed. This article in CodeProject seems to suggest that the dll is unmapped (in the respective process) when the first message arrives at the hooked thread, so it's about right after the UnhookWindowsHookEx() call. Is it true?

Thank you.

like image 956
Gary Chang Avatar asked Dec 18 '10 16:12

Gary Chang


1 Answers

  1. Yes, when a process terminates the system cleans up after it -- all handles are closed implicitly.
  2. No, it's not, and you don't need to anyway.
  3. (It's Yes and no not no and no)
  4. I don't see why there's a DLL loaded in another process involved here. (EDIT: I was originally thinking of a systemwide hook such as CBTProc -- if your hook is per-process that might be different) If you're dealing with something like the link indicated in @Hans' comment, whereby you've injected your own DLL into the target process, then you should put functionality to unload the hook inside your DLL, not tie it's correct operation to your application. (I.e. if sending the message back to your application fails inside the DLL, then your DLL should decide to unload itself) /EDIT When a DLL is loaded inside another process it's up to that process to do the freeing.
like image 166
Billy ONeal Avatar answered Sep 28 '22 12:09

Billy ONeal