[英]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(); 在我的程序中我使用r.exec(); to start the command prompt and execute a bat file in it. 启动命令提示符并在其中执行bat文件。
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. 但是,只要执行上述语句,cmd提示就会启动并执行其中的bat文件。但是,java程序执行不会等到bat文件在提示符中执行,即。 It starts the cmd prompt & starts executing the bat file in it and continues with the execution of next statements after r.exec(); 它启动cmd提示并开始在其中执行bat文件,并继续执行r.exec()之后的下一个语句; .(Meanwhile my bat file is still being executed in the prompt) 。(同时我的bat文件仍在提示中执行)
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. 我的要求是,java程序必须等到执行命令提示符中的bat文件,而不是继续执行next语句。
Runtime.exec
returns a Process
instance. Runtime.exec
返回一个Process
实例。 On that instance you can call waitFor()
to wait for the Process to complete. 在该实例上,您可以调用waitFor()
以等待Process完成。
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. 此外,您需要处理Process.getErrorStream()
和Process.getOutputStream()
(通常在单独的Thread中),以便Process在这些Buffers填满时不会阻塞。 ProcessBuilder
with redirectErrorStream(true)
has a handy method that removes the need to handle two streams at once and therfor the additional thread. 带有redirectErrorStream(true)
ProcessBuilder
有一个方便的方法,它不需要同时处理两个流,也不需要额外的线程。
r.exec("command")
returns Process
. r.exec("command")
返回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. waitFor()
方法将暂停当前线程,直到进程关闭。
Javadoc
waitFor()
: Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated JavadocwaitFor()
:如果需要,使当前线程等待,直到此Process对象表示的进程终止
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. 此外,如果要捕获输入或向控制台发送命令,可以在单独的线程中使用process.getInputStream()
和process.getOutputStream()
。 This would let you monitor the batch file as it runs, so you could cancel terminate process if it breaks down for some reason. 这将允许您在批处理文件运行时监视它,因此如果由于某种原因发生故障,您可以取消终止进程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.