C# process restart loop

China☆狼群 提交于 2019-12-13 15:39:19

问题


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);  
    }

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2466767/c-sharp-process-restart-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!