6

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!

2
  • 3
    What's wrong with process.exitValue()? Commented May 4, 2011 at 16:52
  • I rolled back the last change to the question, in which the OP partially implemented the solution that Peter Lawrey provided. This was a material change to the question and really made it unusable, IMO, to future readers. Commented May 4, 2011 at 17:33

1 Answer 1

18

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.

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)

From the Javadoc for exitValue

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

Sign up to request clarification or add additional context in comments.

5 Comments

he thinks that the argv to echo are interpreted by a shell before echo gets them, but they're not.
Hi Peter, thanks for the comment..but its giving me an error.
@mad-programmer, You need to handle InterruptedException. ;)
when I use waitFor() its just giving me a blank terminal not even a new bash command line..just an empty command line.
You won't see the bash command line. waitFor won't return until the bash script finishes. I suggest you try some thing you know will return to see that it does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.