我如何从Java内部从一个进程中运行bash命令退出code? [英] How do I get the bash command exit code from a Process run from within Java?

查看:157
本文介绍了我如何从Java内部从一个进程中运行bash命令退出code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它是:

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);
       }

     }
    } 

请注意:nv0914是一个bash可执行文件并nv0914.challenge是一个文本文件。
当我在终端和刚过运行任何正常的命令,如果我检查使用回声$退出code {?} 。现在我想用一个程序做同样的,但该方案只是给输出 $ {?} 。请帮助我!

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!

推荐答案

Process.waitFor()返回一个 INT 这是返回的退出code其中。如果你开始一个不相关的程序,不会有previous退出code这就是为什么它不返回任何有用的东西。

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.

您不能使用exitValue()可靠,因为你可以把它叫做程序完成之前。您应该只把它调用WAITFOR(后)(,它会给出相同的退出code WAITFOR()一样)

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)

从的Javadoc exitValue

From the Javadoc for exitValue

抛出:IllegalThreadStateException - 如果此Process对象psented子进程重新$ P $尚未终止

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

这篇关于我如何从Java内部从一个进程中运行bash命令退出code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆