how to make a watchdog?

natarius

Newcomer
Joined
Oct 31, 2005
Messages
11
hi,
i would like to build an watchdog for my app, so that if my main app crashes (freeze, runtime error msg, etc ) the wacthdog restarts it.

so my problem is how to detect if my app has crashed! system.diagnostics doesn't provide any functions to detect if an process has crashed!

i was thinking about writing some timestamp into a file and if after a period of time there wasn't a update, the watchdog will asume that the app has crashed!

does anyone here have a better idea?

thx & greets

matthias
 
You may not be able to check for a crashed process but you can test for a running process, if the process is no longer running, you start it again. I guess thats assuming that the crashes exit the process which is not neccessarily the case though. You may also wish to try some networking style code, sending a ping / pong event to each other every few minutes as in IRC. Not sure how well that would work on a single pc but it should be possible.
 
Here's something I just tried - seems to work, though it may need tweaking for you.

In your watchdog:
C#:
using System;
using System.Diagnostics;

namespace MyWatchdog
{
	internal sealed class EntryPoint
	{
		[STAThread]
		static void Main() 
		{
			Process process;
			do
			{
				process = Process.Start(@"c:\test.exe");
				process.WaitForExit();
			} while(process.ExitCode != 0);
		}
	}
}

This will keep running c:\test.exe until it returns 0 (success).

The key is to now have your main program return it's status. Here's what I did:
C#:
using System;

namespace MyProject
{
	internal sealed class EntryPoint
	{
		private EntryPoint() {}

		[STAThread]
		static void Main() 
		{
			System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
			System.Windows.Forms.Application.Run(new Form1());
		}

		private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
		{
			System.Environment.ExitCode = 1;
			System.Windows.Forms.Application.Exit();
		}
	}
}

The key is that the program now traps any unhandled errors in the event ThreadException. This handler simply sets the ExitCode and then shuts down with Application.Exit. This would be your place to cleanup any resources before shutting down.

-ner
 
You could also just use a batch file, which may require less system resources.

Open a text file in notepad, type:
Code:
:Start
echo (%time%) Started.
start /wait myapp.exe
goto Start
Save as StartUp.bat

Double click the file and you're off :)

This wouldn't be a solution to distribute to a client, but is perfectly suitable for personal use.
 
Back
Top