Here is a simple example how to use Process.WaitForExit
to check for a parent process whose id has been passed on the command line:
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static AutoResetEvent _autoResetEvent;
static void Main(string[] args)
{
int parentProcessId = int.Parse(args[0]);
_autoResetEvent = new AutoResetEvent(false);
WaitCallback callback = delegate(object processId) { CheckProcess((int)processId); };
ThreadPool.QueueUserWorkItem(callback, parentProcessId);
_autoResetEvent.WaitOne();
}
static void CheckProcess(int processId)
{
try
{
Process process = Process.GetProcessById(processId);
process.WaitForExit();
Console.WriteLine("Process [{0}] exited.", processId);
}
catch (ArgumentException)
{
Console.WriteLine("Process [{0}] not running.", processId);
}
_autoResetEvent.Set();
}
}
Using the Process.Exited
event could be done like this:
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static AutoResetEvent _autoResetEvent;
static void Main(string[] args)
{
int parentProcessId = int.Parse(args[0]);
Process process = Process.GetProcessById(parentProcessId);
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(process_Exited);
_autoResetEvent = new AutoResetEvent(false);
_autoResetEvent.WaitOne();
}
static void process_Exited(object sender, EventArgs e)
{
Console.WriteLine("Process exit event triggered.");
_autoResetEvent.Set();
}
}
Note that in both samples the purpose of the AutoResetEvent
is solely to prevent your main thread from exiting. In a Windows Forms application you would not need to use it as your program will be in a message loop and only exit if you close it.