Skip to main content
 首页 » 编程设计

c#之如何检测进程执行的应用程序是否由于无效输入而停止工作

2024年02月23日18webabcd

我想创建一个 LaTeX 编辑器来生成 pdf 文档。 在后台,我的应用程序使用通过 Process 实例执行的 pdflatex.exe。

pdflatex.exe 需要输入文件,例如 input.tex 如下

\documentclass{article} 
\usepackage[utf8]{inputenc} 
\begin{document} 
\LaTeX\ is my tool. 
\end{document} 

为了简单起见,这里是我的 LaTeX 编辑器中使用的最小 c# 代码:

using System; 
using System.Diagnostics; 
 
namespace ConsoleApplication1 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Process p = new Process(); 
 
            p.EnableRaisingEvents = true; 
            p.Exited += new EventHandler(p_Exited); 
 
            p.StartInfo.Arguments = "input.tex"; 
            p.StartInfo.UseShellExecute = false; 
            p.StartInfo.FileName = "pdflatex.exe"; 
 
            p.Start(); 
            p.WaitForExit(); 
        } 
 
        static void p_Exited(object sender, EventArgs e) 
        { 
            // remove all auxiliary files, excluding *.pdf. 
        } 
    } 
} 

问题是

如何检测pdflatex.exe是否因为无效输入而停止工作?

编辑

这是最终的工作解决方案:

using System; 
using System.Diagnostics; 
 
namespace ConsoleApplication1 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Process p = new Process(); 
 
            p.EnableRaisingEvents = true; 
            p.Exited += new EventHandler(p_Exited); 
 
            p.StartInfo.Arguments = "-interaction=nonstopmode input.tex";// Edit 
            p.StartInfo.UseShellExecute = false; 
            p.StartInfo.FileName = "pdflatex.exe"; 
            p.StartInfo.RedirectStandardError = true; 
            p.Start(); 
            p.WaitForExit(); 
 
            //Edit 
            if (p.ExitCode == 0) 
            { 
                Console.WriteLine("Succeeded..."); 
            } 
            else 
            { 
                Console.WriteLine("Failed..."); 
            } 
        } 
 
        static void p_Exited(object sender, EventArgs e) 
        { 
            // remove all  files excluding *.pdf 
 
            //Edit 
            Console.WriteLine("exited..."); 
        } 
    } 
} 

使用-interaction=nonstopmode 的想法属于@Martin here .

请您参考如下方法:

大多数命令行应用程序都会设置一个退出代码来指示成功或失败。你这样测试它:

p.WaitForExit(); 
if (p.ExitCode == 0) { 
    // Success 
} else { 
    // Failure 
}