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

时间:2021-10-22 22:49:10

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。挑战是一个文本文件。当我在终端上运行任何普通的命令时,然后如果我使用echo ${?}检查退出代码。现在我想通过使用一个程序来做同样的事情,但是这个程序只是给输出${?}。请帮帮我!

1 个解决方案

#1


17  

Process.waitFor() returns an int That 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.

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

来自Javadoc的exitValue

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

抛出:IllegalThreadStateException—如果该进程对象表示的子进程尚未终止。

#1


17  

Process.waitFor() returns an int That 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.

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

来自Javadoc的exitValue

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

抛出:IllegalThreadStateException—如果该进程对象表示的子进程尚未终止。