如何从 Java 中运行的进程中获取 bash 命令退出代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5886935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:56:12  来源:igfitidea点击:

How do I get the bash command exit code from a Process run from within Java?

javabashunixexit-coderuntime.exec

提问by Maverick

I have a program which is:

我有一个程序是:

import java.io.*;
   import java.util.*;

   public class ExecBashCommand {
     public static void main(String args[]) throws IOException {

       if (args.length <= 0) {
         System.err.println("Need command to run");
         System.exit(-1);
       }

       Runtime runtime = Runtime.getRuntime();
       Process process = runtime.exec("./nv0914 < nv0914.challenge");
       Process process1 = runtime.exec("echo ${?}");
       InputStream is = process1.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);
       String line;

       //System.out.printf("Output of running %s is:", Arrays.toString(args));

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

     }
    } 

note: nv0914 is a bash executable file and nv0914.challenge is a text file. When i run any normal command in terminal and just after that if I check the exit code using echo ${?}. Now I want to do the same by using a program, but the program is simply giving the output ${?}. Please help me out!

注意:nv0914 是一个 bash 可执行文件,而 nv0914.challenge 是一个文本文件。当我在终端中运行任何正常命令时,如果我使用echo ${?}. 现在我想通过使用一个程序来做同样的事情,但该程序只是给出了 output ${?}。请帮帮我!

回答by Peter Lawrey

Process.waitFor() returns an intThat is where the exit code is returned. If you start an unrelated program, won't have a previous exit code which is why it doesn't return anything useful.

Process.waitFor() 返回一个int那就是退出代码的返回位置。如果您启动一个不相关的程序,则不会有之前的退出代码,这就是为什么它不会返回任何有用的信息。

You can't use exitValue() reliably because you could call it before the program has finished. You should only call it after calling waitFor() (and it will give the same exit code waitFor() does)

您不能可靠地使用 exitValue() ,因为您可以在程序完成之前调用它。你应该只在调用 waitFor() 之后调用它(它会给出与 waitFor() 相同的退出代码)

From the Javadoc for exitValue

来自 exitValue 的 Javadoc

Throws: IllegalThreadStateException - if the subprocess represented by this Process object has not yet terminated.

抛出: IllegalThreadStateException - 如果此 Process 对象表示的子进程尚未终止。