34. I start another app and try and wait synchronously on its process handle, but both processes hang. Why?
This situation arises when you use ShellExecuteEx
or CreateProcess to start another application from your GUI application, then
try to wait synchronously using WaitForSingleObject on its process handle.
The problem arises because your application has a
window but isn't pumping messages. If the spawned application invokes
SendMessage with one of the broadcast targets (HWND_BROADCAST or HWND_TOPMOST),
then the SendMessage won't return to the new application until all applications
have handled the message - but your app can't handle the message because it
isn't pumping messages.... so the new app locks up, so your wait never
succeeds.... DEADLOCK.
If you have absolute control over the spawned
application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody
is still using that). But there are situations which cause implicit SendMessage
broadcasts over which you have no control, such as using the SetSysColors API
for instance.
The only safe ways round this are (a) split off
the Wait into a separate thread, or (b) use a timeout on the Wait and use
PeekMessage in your Wait loop to ensure that you pump messages. You could also
try using the MsgWaitForMultipleObjects API, but that's not the easiest function
in the world to get your head around....