开发者

How to tell if process was forced closed (WaitForExit) has been triggered?

I am making a call to ffmpeg. Sometimes the call fails and ffmpeg wont exit it will just enter a recursive loop. I have called the WaitForExit mthod.

Further on in the code I am interrogating the standardOutput and standardError. I know that when ffmpeg doesnt exit it produces alot of garbage on the console screen. For that reason I believe when I try and get the standardOutput and standardError the c# code just crashes. Its still being written to. How can I tell if c# has exited the code rathar than the process exiting on its own?

I have tried to look at process.HasExited but it doesnt work. Even though I know c# has exited the process it still comes up as false.

            p.StartInfo.FileName = exePathArg;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.Arguments = argumentsArg;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.Start();

            p.WaitForExit(timeToWaitForProcessToExit);

            StreamReader standardOutput = p.StandardOutput;
            StreamReader standardError = p.StandardError;

            retDirects.Add("StandardOutput", standardOutput.ReadToEnd());
            retDirects.Add("StandardError", standardError.ReadT开发者_如何学CoEnd());


You might not be able to tell unless the process provides some sort of output or error code. You can look at the ExitCode using:

p.ExitCode

The error code is provided by the application, so you'll also have to be aware of what values it might return.

In some cases if the process is killed (e.g. via task manager, ExitCode may be 1, see this answer).

Update

After our exchange in the comments, it seems that there were some other issues to address:

If you're confident that the process is actually in an unresponsive state, then killing the process is a good last resort. There are two ways to "kill" a process with the Process class:

  • Process.Kill() - terminate the process (and possibly corrupt data)
  • Process.CloseMainWindow() - sends close message to the main window (only GUI procs)

If you have a process with a graphical interface, you should use CloseMainWindow(). CloseMainWindow() is essentially the same thing as clicking the exit button on a window, so it is safer because it actually asks the program to shut itself down. Note that the process might not actually respond to CloseMainWindow, either because it is unresponsive or because it chooses not to, so you may have to use Kill() afterwards if that happens.

If your process doesn't have a graphical interface, Kill() is the only way to do it.

However, as you asked in the comments about using both, you shouldn't do that unless you tried to use CloseMainWindow() and that didn't work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜