1

When I am running the batch command ping 127.0.0.1 -n 5 > nul (waits 5 seconds) in Java "directly":

public class Test {
          public static void main(String[] args) throws IOException, InterruptedException {
    
              Process testProcess =  Runtime.getRuntime().exec("ping 127.0.0.1 -n 5 > nul");
              testProcess.waitFor();
              System.out.println("foo");
          }
}

the String "foo" prints out instant and not after 5 seconds, even the .waitFor() method should make the thread wait, until the process is finished.

But when I change testProcess to Runtime.getRuntime().exec("C:/Users/Desktop/test.bat") to execute a Batch file, which has only the command ping 127.0.0.1 -n 5 > nul inside it, the .waitFor()method waits until the process is finished. So that the "foo" is printed after 5 seconds.

Why is that so?


EDIT:

I needed to remove > nul (see @Generous Badger 's comment)

Steve450
  • 113
  • 2
  • 7
  • 3
    Have you checked the return value of `waitFor`? The `>` is not interpreted by `Runtime.exec()`, handling redirects like that is usually done by a shell and no shell is involved here. Try to remove the `> nul` and use `ProcessBuilder.redirectOutput()` to output redirect the output to wherever you want instead. – Generous Badger Jun 16 '21 at 08:34
  • Ah yeah thanks, I needed to remove the `> nul`, then it works without `ProcessBuilder` or batch file – Steve450 Jun 16 '21 at 08:37
  • 1
    `ping 127.0.0.1 -n 5` waits for **4** seconds (5 attempts with 4 pause intervals of a second each)! – aschipfl Jun 16 '21 at 08:44
  • If for some reason you needed some redirection you would have to explicitly invoke the Command Interpreter by `cmd /C ping 127.0.0.1 -n 5 > nul`… – aschipfl Jun 16 '21 at 08:46

0 Answers0