views:

51

answers:

2

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.

A: 

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.

Stephen Cleary
Interesting possibility -- though in production, we don't want the apps waiting on each other, so I would need to make the wait-on-exit conditional on something like an environment variable. This also won't work if app A crashes -- which, especially since this is used on developer machines, does happen from time to time...
Joe White
Another possibility is the "right" way (which I did not recommend due to its complexity)... Wrap the parent in a [job object](http://www.microsoft.com/msj/0399/jobkernelobj/jobkernelobj.aspx). This solution will include all processes (e.g., Notepad), and requires non-trivial p/Invoke, especially for the "all processes exited" signal.
Stephen Cleary
A: 

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.

jdot
Polling isn't exactly elegant, but this could work.
Joe White
Agreed, but I cannot think of another way to get it working unless waiting for each child process to finish. Cannot shutdown App A until App B closes. Possibly changing the launcher to launch all applications. Not apps launching other apps.
jdot