How can I wait until a Windows process, and its su

2019-08-01 02:17发布

问题:

We have a launcher app that does some setup (starting a server), launches a child process, waits (via a worker thread) for the child process to exit, and then does some cleanup (stopping the server). This is already in place and works fine.

However, some of our apps can launch other apps. So for example, the launcher might start app A, and then I might click a button in app A that starts app B. Then I close app A, the launcher's Process.WaitForExit call returns, and the launcher stops the server -- unaware that app B is still running. We only use the launcher for development testing, so this isn't a crisis, but it's inconvenient when app B tries to talk to the server and crashes.

What's the best way to start a child process, and then wait for it (and any of its children) to exit?

These apps (both the launcher and the apps being launched) are all in .NET. It's fine if I have to write special code (e.g. opening a named semaphore) in each app to make this work; I'm just not sure of the best way to do it.

Bonus points if there's some way to only wait for my apps to finish -- e.g., if my app launches Notepad, I don't want to wait for Notepad to close; I just want to wait on apps that need the server. But this isn't a requirement, just a nicety.

回答1:

Change the condition of the server shutting down in the launcher app. Only shutdown the server, if none of your process names are running. You can periodically check for your process names. Shutdown the server if none found.



回答2:

Actually, the easiest way to do this is to have the parent process wait for its child process(es), and then just wait for the parent process as you are doing. You can choose exactly which ones to wait for that way.