Question

I'm trying to make a console app that would monitor some process and restart it if it exits. So, the console app is always on, it's only job is to restart some other process.

I posted my code below.. it basically works but just for one process restart...

I would appreciate any help!!

Thanks in advance!

    {
        System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName(SOME_PROCESS);
        p[0].Exited += new EventHandler(Startup_Exited);

        while (!p[0].HasExited)
        {
            p[0].WaitForExit();
        }

        //Application.Run();
    }

    private static void Startup_Exited(object sender, EventArgs e)
    {
        System.Diagnostics.Process.Start(AGAIN_THAT_SAME_PROCESS);  
    }
Was it helpful?

Solution

You need a loop, and at the top of the loop you need to reattach p to the new process after restarting the program. So something like:

Process p = /* get the current instance of the program */;
while (true)
{
  p.WaitForExit();
  p = Process.Start(/* the program */);
}

Note that since Process.Start returns the Process object for the new instance, you don't actually need to re-perform the search: you can just wait directly on the new Process object.

OTHER TIPS

I'd be willing to bet that, upon starting your process again, you need to update the process that p[0] is pointing to and reattach your event handler. It appears that once it dies, your event fires and you never have an event handler registered with a process again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top