Wednesday, August 30, 2006 9:19 PM
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).
public static void Main()
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);
private static void LaunchAgain(object o, EventArgs e)
Console.WriteLine("Process was killed; launching again");
!!! Warning !!!
- Don't use this to annoy people with a non-disappearing prgram.
- 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.
- 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
Filed under: .NET Framework v2.0, C# 2.0