tags:

views:

92

answers:

3

So i have a helper process written in C++ and I open it, feed it arguments, and it feeds my program back information through the standardoutput stream.

PS. I don't have the source for the helper process exe.

If my application were to be terminated from the task manager, or for some reason crash, how could I ensure that my helper exe is closed? Is this possible? Would I need an external file?

A: 

You should create an inheritable duplicate of the parent process handle and pass its value to the helper process on the commandline. The helper process can then wait on that handle on a separate thread (or the main thread if you're clever). When the handle becomes signaled, it means that the launching process has terminated.

Edit

Since you can't change the helper process, your options are more limited. Your could try attaching a handler to the launching process's OnAppDomainUnloaded event, but I'm not sure this will work in all the cases you're concerned about. You could also create a third process to monitor the first. This process would work as I described above. If you wanted to get really fancy, you could inject a remote thread into the helper process to monitor the parent. This is very technical, so I recommend against it.

Peter Ruderman
Could you go into that in a little more detail?
Tommy
How much detail do you need?
Peter Ruderman
Well I don't have the source for the helper executable for one.
Tommy
Sorry. I totally missed that. I'll modify my answer.
Peter Ruderman
+2  A: 

Use Job Objects to manage groups of processes. In this case you want to create a job object using CreateJobObject, use SetInformationJobObject to set the JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE flag, and assign the helper process to the job using AssignProcessToJobObject. Don't close the handle to the job object unless you want to kill the helper process. When your process terminates (through any means), the handle will be closed and your helper process will be killed.

wj32
@WJ32: good answer, but please don't post version-specific MSDN links unless the information is version-specific.
John Saunders
Sorry, didn't notice that.
wj32
A: 

The easiest way would be to close it on normal application exit and when AppDomain.CurrentDomain.UnhandledException is invoked (i.e. your app is about to crash)

jgauffin