Wednesday, August 30, 2006 9:19 PM bart

A simple process monitor - monitoring and restarting a process

The problem statement

One of my friends asked me how to implement some kind of "process monitor" that makes sure a (system) process stays alive. In this sample I'm showing you how to implement such a thing in C#. An alternative situation would be to monitor a Windows Service but the SCM (Service Control Manager) in Windows can take care of that (tab Recovery).

The code

using System;
using
System.Diagnostics;

class
Demo
{
   public static void
Main()
   {
      Launch();
      Console
.ReadLine();
   }

   private static void
Launch()
   {
      ProcessStartInfo psi =
new
ProcessStartInfo();
      psi.FileName =
"notepad.exe"
;

      Process p =
new
Process();
      p.StartInfo = psi;
      p.EnableRaisingEvents =
true
;
      p.Exited +=
LaunchAgain; //C# 2.0 syntax - alternative: p.Exited += new EventHandler(LaunchAgain);

      p.Start();
   }

   private static void LaunchAgain(object o, EventArgs
e)
   {
      Console.WriteLine("Process was killed; launching again"
);
      Launch();
   }
}

!!! Warning !!!

  1. Don't use this to annoy people with a non-disappearing prgram.
  2. Of course, the monitoring process can still crash (or be terminated). This is a chicken-egg situation but of course you can't create an endless chain of monitors.
  3. Security matters! A process that crashes can be the indication of a security problem or risk (e.g. a compromised service). In case of unmanaged code a buffer overrun (maybe as part of an attack) could be the reason the process stops. So, you shouldn't restart the process forever. It's better to have a maximum amount of automatic process restarts, just like the SCM only permits three service restarts.

Keep it alive and have fun!

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under: ,

Comments

# re: A simple process monitor - monitoring and restarting a process

Wednesday, August 30, 2006 9:43 PM by Bassam Basamad

Thanks..
It seem to be userfull example..

Best Regards