java - Java中如何检查进程是否有错误?

标签 java process

我正在 JavaFx 中制作 IDE 相关程序,运行 C、C++、Python 等代码。 当用户代码中存在任何编译时/运行时错误时,它会在弹出窗口中显示一些与堆栈溢出相关的错误的答案。但是,我怎么知道是否有错误呢?

我的代码片段在这里 -

public BufferedReader buildCode(File file)
    {
        String dirname = file.getParent();
        String filePath = file.getPath();
        String fileName = file.getName();
        String objectFileName = FilenameUtils.removeExtension(fileName);
        String command = "gcc " + filePath + " -o " + dirname + "/" + objectFileName;
        BufferedReader stdInput;// = new BufferedReader(null);
        try
        {
            Process process = Runtime.getRuntime().exec(command);
            stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String compileResult;
            while ((compileResult = stdInput.readLine()) != null)
                System.out.println(compileResult);

            while ((compileResult = stdErr.readLine()) != null)
                System.out.println(compileResult);
            return stdInput;
        }
        catch (IOException io)
        {
            //noinspection ThrowablePrintedToSystemOut
            System.out.println(io);
            return null;
        }
    }

我想我必须做一些事情,比如检查stdErr,无论它是否为空。但是,我不确定是否没有任何错误,它会在 stdErr 中分配 EOF

最佳答案

无需解析进程的输出。海湾合作委员会will return non-zero exit code如果出现问题:

Normally the gcc program exits with the code of 1 if any phase of the compiler returns a non-success return code. If you specify -pass-exit-codes, the gcc program instead returns with the numerically highest error produced by any phase returning an error indication. The C, C++, and Fortran front ends return 4 if an internal compiler error is encountered.

因此,您只需检查退出代码即可:

final Process process = Runtime.getRuntime().exec(command);

process.waitFor();

final result = process.exitValue();

if(0 != result) {
  ...
}

关于java - Java中如何检查进程是否有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059314/

相关文章:

java - 如何正确地将值赋给对象数组?

java - Jackson json 双向对象引用

Java从JTextField存储变量以用于公式

java - 将 CSV 文件读入不同类型的数组,然后读入 Arraylist

android - 如何在 Linux 中未崩溃时显式转储 native (C/C++)进程的调用堆栈信息

linux - 关于Linux进程内存布局的问题

project-management - 您的 Web 开发过程由哪些步骤组成,每个阶段需要多长时间?

C++ Windows CreateChildProcess - 隐藏/不显示子进程的控制台窗口

Perl,等待非子进程退出

java - 使用 Thymeleaf 处理电子邮件 html