Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

java - Runtime.exec().waitFor() doesn't wait until process is done

I have this code:

File file = new File(path + "\RunFromCode.bat");
file.createNewFile();

PrintWriter writer = new PrintWriter(file, "UTF-8");
for (int i = 0; i <= MAX; i++) {
    writer.println("@cd " + i);
    writer.println(NATIVE SYSTEM COMMANDS);
    // more things
}

writer.close();

Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\RunFromCode.bat");
p.waitFor();

file.delete();

What happens is that the file deleted before it actually executed.

Is this because the .bat file contains only native system call? How can I make the deletion after the execution of the .bat file? (I don't know what the output of the .bat file will be, since it dynamically changes).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By using start, you are askingcmd.exe to start the batch file in the background:

Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\RunFromCode.bat");

So, the process which you launch from Java (cmd.exe) returns before the background process is finished.

Remove the start command to run the batch file in the foreground - then, waitFor() will wait for the batch file completion:

Process p = Runtime.getRuntime().exec("cmd /c " + path + "\RunFromCode.bat");

According to OP, it is important to have the console window available - this can be done by adding the /wait parameter, as suggested by @Noofiz. The following SSCCE worked for me:

public class Command {

public static void main(String[] args) throws java.io.IOException, InterruptedException {
       String path = "C:\Users\andreas";

       Process p = Runtime.getRuntime().exec("cmd /c start /wait " + path + "\RunFromCode.bat");

       System.out.println("Waiting for batch file ...");
       p.waitFor();
       System.out.println("Batch file done.");
   }
}

If RunFromCode.bat executes the EXIT command, the command window is automatically closed. Otherwise, the command window remains open until you explicitly exit it with EXIT - the java process is waiting until the window is closed in either case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...