Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for the cmd command to get executed before running the next command?

Tags:

java

Need to wait for the cmd command to get executed before running the display function.

Need the Process p to get executed completely before executing display function.

String command1 = "cmd /c start cmd.exe /k \"" + processCommand1 + " && " + processCommand2  +" && "+ exitCommand+"\"";

Process p = Runtime.getRuntime().exec(command1);

display();
like image 851
Divyanshu Avatar asked Feb 04 '19 12:02

Divyanshu


People also ask

How do you delay in cmd?

Syntax TIMEOUT delay [/nobreak] Key delay Delay in seconds (between -1 and 100000) to wait before continuing. The value -1 causes the computer to wait indefinitely for a keystroke (like the PAUSE command) /nobreak Ignore user key strokes.

How do you wait for a batch command to finish?

Use /WAIT to Wait for a Command to Finish Execution When we start a program in a Batch file using the START command, we can wait until the program is finished by adding /wait to the START command. Even if there are multiple commands, /wait can be used for each process to finish and move to the next one.

What is Pause command in cmd?

Pause syntaxSuspends processing of a batch program and displays the message: Press any key to continue.

How do I keep cmd open after execution?

Type the "cmd /k" parameter before every command to keep the window from closing.


2 Answers

One way would be to use Process.waitFor(). However in your example you are using cmd /c start which will run the actual program asynchronously in the background. You should ensure that the program is started synchronously without start so you can wait for it.

like image 188
Karol Dowbecki Avatar answered Nov 07 '22 21:11

Karol Dowbecki


Better to use java.lang.ProcessBuilder. JavaDoc had example: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html Something like that:

ProcessBuilder processBuilder = new ProcessBuilder("...");
...
Process process = processBuilder.start();
...
int exitCode = process.waitFor();
like image 26
Gmugra Avatar answered Nov 07 '22 19:11

Gmugra