How to determine when spawned process is ready? (Using CreateProcess() and FindWindow())

StackOverflow https://stackoverflow.com/questions/4107499

  •  29-09-2019
  •  | 
  •  

문제

This should be an easy one: I am creating a program that spawns a process using the win32 CreateProcess() function. Once this process is loaded, I find its window using FindWindow and send it messages using SendMessage(). The question is, how do I know when that window is ready to accept messages?

Consider the following:

HWND wnd;

BOOL Start()
{
  // Spawn the process
  if (! CreateProcess(...))
    return FALSE;

  // Find the process's window (class and name already known)
  wnd = FindWindow(MY_WINDOW_CLASS, MY_WINDOW_NAME);

  // Always returns FALSE because window has not yet been created.
  return (wnd != NULL);
}

The code above will (almost?) always fail; the window cannot be created and found that quickly. If I put a thread wait, say Sleep(1000), between the CreateProcess and FindWindow calls, it works fine. But this feels like a very bad hack.

How can I improve this?

도움이 되었습니까?

해결책

(Edit): User IInspectable pointed out problems with WaitForInputIdle(), and suggested CBT Hooks instead.

(...) callback function used with the SetWindowsHookEx function. The system calls this function before activating, creating, (...) a window; (... many other things).

Also, CBT is short for computer-based training, for whatever reason.

(Old, beware, see comments.) You are looking for WaitForInputIdle(). Quote:

When a parent process creates a child process, the CreateProcess function returns without waiting for the child process to finish its initialization. Before trying to communicate with the child process, the parent process can use the WaitForInputIdle function to determine when the child's initialization has been completed.

다른 팁

Have you looked at WaitForInputIdle?

If the process you're starting is one you can change, have it send a message back to the parent when it is ready. You can pass the HWND of the parent as a command line parameter, or use FindWindow if you can guarantee that the parent will be unique.

I assume that the source code of both processes is under your control.

  • You can let the second process post a message to the first when it's ready, if the second knows the needed details of the first process' message window.
  • Or you can wait in the first process for an agreed-upon named synchronization object, like event or mutex, being set from the second process.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top