Basically the child process runs indefinitely until killed in the background, and I want to clean it up when my program terminates for any reason, i.e. via the Taskmanager.
Currently I have a while (Process.GetProcessesByName(‘ParentProcess’).Count() > 0) loop and exit if the parent process isn’t running, but it seems pretty brittle, and if I wanted it to work under debugger in Visual Studio I’d have to add ‘ParentProcess.vshost’ or something.
Is there any way to make sure that the child process end without requiring the child process to know about the parent process? I’d prefer a solution in managed code, but if there isn’t one I can PInvoke.
Edit: Passing the PID seems like a more robust solution, but for curiosity’s sake, what if the child process was not my code but some exe that I have no control over? Is there a way to safeguard against possibly creating orphaned child processes?
If the child process is your own code, you could pass it the PID of the parent process when you launch it. The child process could then fetch the process with
Process.GetProcessByIdand subscribe to itsExitedevent with a handler which shuts down the rest of the (child) process gracefully. Note that you need to set theEnableRaisingEventsproperty on the process totrue.