0

I've been working on a small piece that calls an external executable (ffmpeg in my case) And then I wrote a test and used test runner in a debug mode, now if I stop debugging (terminate) it still runs ffmpeg. I tried to kill the process in the finalizer and with IDisposable - it still runs. How can I make sure that the process never will be left like that, and if the caller dies or fails or gets stopped by any means, the ffmpeg executable guaranteed to be killed.

I run the process as usual (nothing fancy)

var processInfo = new ProcessStartInfo(ffmpegPath)
{
    UseShellExecute = false,
    Arguments = arguments,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
};

using (var ffmpegProc = new Process())
{
    ffmpegProc.EnableRaisingEvents = true;
    ffmpegProc.StartInfo = processInfo;
    ffmpegProc.Start();
    ffmpegProc.WaitForExit();
}
iLemming
  • 34,477
  • 60
  • 195
  • 309

2 Answers2

1

There is nothing you can do when your process is terminated. There is no code run in your process after someone kills it with TerminateProcess call.

In case of more graceful cases (i.e. unhandled exception) you may have global handler that does something close to what you want.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • so then how do I test that? How can I write and run a test to make sure, that process gets killed if the main process has terminated? – iLemming Mar 04 '13 at 16:57
  • 1
    @Agzam, what do you need to test - "all child processes reasonably terminated on normal end of main process" or something else? If normal shutdown - you can notify your process in some way to exit instead of killing it. – Alexei Levenkov Mar 04 '13 at 17:41
1

You should use JobObject

With JobObject you can add child processes. So if the main process is killed or closed the os will terminate all child processes.

source: http://www.xtremevbtalk.com/showpost.php?p=1335552&postcount=22

Another solution is to pass to child object the parent PID.

Any child have to check for parent PID existence and if not found kill itself

giammin
  • 18,620
  • 8
  • 71
  • 89
  • I doesn't look like a very simple solution though. I'm gonna try to use jobobjectwrapper.codeplex.com, although the project looks a bit old, still let me see if I can reuse it – iLemming Mar 04 '13 at 17:22
  • @Agzam I agree with you. I don't know if the PID solution is suitable in your situation – giammin Mar 04 '13 at 17:23
  • @Agzam did you try Process.Exited Event? http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx – giammin Mar 04 '13 at 17:36
  • 1
    @Agzam, if you decide to go this route make sure to understand OS version differences. To my knowledge there are some serious restrictions on creating child jobs in pre-Windows-8 versions. – Alexei Levenkov Mar 04 '13 at 17:38