Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make runtime.getruntime().exec(String command) return a boolean value?

I am trying to use runtime.getruntime().exec(String command) to return a value so that I can make the system decide on executing it again or not. Is there a solution for this?

like image 393
Sandeep Avatar asked Jun 10 '26 15:06

Sandeep


2 Answers

Runtime.exec returns a Process, process has a method called waitFor, which will wait for the running process to terminate and return.

Process has a method called exitVaue, which returns an int returning the exit state of the program. Convention suggests that 0 is an indication of a normal termination, but this might be contextual to the program you are running.

You would need to...

  1. Know what is a valid exit value for the process your are running
  2. Check the exitValue returned by the instance of Process against the known valid exit values.

Things to note...

  • Generally, you should be consuming the InputStreams (input and error) of the Process, as failing to do so can cause some processes to stall
  • ProcessBuilder is generally a better solution as has better functionality when it comes to dealing with multiple parameters for the command, has redirection and can even determine the starting directory context for the command...
like image 167
MadProgrammer Avatar answered Jun 13 '26 05:06

MadProgrammer


Runtime runtime = Runtime.getRuntime();
       Process process = runtime.exec(args);
       InputStream is = process.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);
       }
like image 34
Shriram Avatar answered Jun 13 '26 06:06

Shriram