0

I want to execute this command within my java program and check if it was successfully executed.

 sudo ntpdate -u someserver.com

I create a bash with the command

#!/bin/sh
sudo ntpdate -u omeserver.com

and execute it with java

ProcessBuilder pb = new ProcessBuilder("/updateTime");
    Process p = pb.start();     
    p.waitFor();             
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    System.out.println(stdInput.readLine());

But I get no output, there are no lines in stdInput, how can I check if the command was correctly executed?

If I add for example Echo updated in the end of the bash file I get it in the stdInput, but it still don't mean that the time were updated

lisa
  • 9
  • 1
  • Does the script execute successfully in a terminal? Does the `sudo` prompt for a password? – starf Oct 03 '16 at 18:41
  • yes it execute successfully and no no password needed – lisa Oct 04 '16 at 18:34
  • Do you have anything on stderr? Try changing `p.getInputStream()` to `p.getErrorStream()`. I have tried a similar script and cannot reproduce your issue. – starf Oct 04 '16 at 19:01

1 Answers1

0

You'd probably get by easier when just calling sudo directly with ProcessBuilder instead of an external script. That's just redundant complexity for the task at hand.

You can feed ProcessBuilder with the whole command line, for example, like this:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class q39836547 {
  private static String[] cmdl = { "/usr/bin/sudo",
                                   "ntpdate",
                                   "-u",
                                   "some.ntp.server" };
  public static void main(String[] as) throws IOException {
    ProcessBuilder pb = new ProcessBuilder(cmdl);
    Process p = pb.start();
    BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    try { p.waitFor(); }
    catch(InterruptedException e) { }

    if(p.exitValue() != 0)
      System.err.println("The process was not executed successfully.");
    else
      System.err.println("The process ran and exited cleanly.");

    stdin.lines().forEach(s -> System.out.println("STDOUT: " + s));
    stderr.lines().forEach(s -> System.out.println("STDERR: " + s));
  }
}

You also have to waitFor() (as you properly did) the ntpdate to finish. Otherwise you might end up reading its standard input or standard error with getInputStream() or getErrorStream() before there is any output produced into either stream.

If you comment out the try-catch-block, you'll occasionally see how the process is still running while you're trying to read its input. That is likely to happen almost every time, actually.