简体   繁体   中英

How to stop the execution of my java program after i invoke r.exec to start a cmd prompt

in my program i am using r.exec(); to start the command prompt and execute a bat file in it.

But what happens is, as soon as the above statement is executed cmd prompt starts and executes the bat file in it.However, the java program execution will not wait until the bat file is executed in the prompt ie. It starts the cmd prompt & starts executing the bat file in it and continues with the execution of next statements after r.exec(); .(Meanwhile my bat file is still being executed in the prompt)

My requirement is that, java program must wait until the bat file in command prompt is executed rather than continuing with the execution of next statements.

Runtime.exec returns a Process instance. On that instance you can call waitFor() to wait for the Process to complete.

In addition you need to handle Process.getErrorStream() and Process.getOutputStream() (usually in a separate Thread) so the Process will not block when these Buffers fill up. ProcessBuilder with redirectErrorStream(true) has a handy method that removes the need to handle two streams at once and therfor the additional thread.

r.exec("command") returns Process . From here you can simply put the following:

Process process = r.exec("command here");
process.waitFor(); //Waits until process closes

The waitFor() method will pause this current thread until the process has closed.

Javadoc waitFor() : Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated

Further more, if you want to capture input or send commands to the console, you could use process.getInputStream() and process.getOutputStream() in separate threads. This would let you monitor the batch file as it runs, so you could cancel terminate process if it breaks down for some reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM