我正在 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/