process = Runtime.getRuntime().exec(command); final Process p = process; //close process's output stream. p.getOutputStream().close(); pIn = process.getInputStream(); outputGobbler = new StreamGobbler( pIn, "OUTPUT"); outputGobbler.start(); pErr = process.getErrorStream(); errorGobbler...
推荐使用ProcessBuilder这个新加入的类来替换Runtime.getRuntime().exec,可以自动处理特殊字符,并且接口也要更加丰富和方便使用。 然后,即使只是调用了很简单的脚本命令,在调用Process.waitFor()后都有可能发生无休止或者接近于无休止的阻塞,所以在代码中加入超时控制是必须的。但是Process.waitFor()本身并不支持超时时间...
下面是waitFor()方法的使用示例: public class Main { public static void main(String[] args) { try { // 执行命令 Process process = Runtime.getRuntime().exec("your_command"); // 等待子进程完成执行 int exitCode = process.waitFor(); // 输出子进程的退出码 System.out.println("子进程退出码...
public abstract int waitFor() throws InterruptedException 导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。如果已终止该子进程,此方法立即返回。如果没有终止该子进程,调用的线程将被阻塞,直到退出子进程。 返回: 进程的出口值。根据惯例,0 表示正常终止。 抛出: InterruptedException - ...
在Java中,`Process.waitFor()`方法会阻塞当前线程,直到子进程完成。如果你发现`Process.waitFor()`方法卡住了,可能是由于以下原因之一导致的:1. 子进程没有正...
ProcessBuilder类提供了设置规定时间的方法,例如使用ProcessBuilder#start()方法启动进程后,您可以使用Process#waitFor(long timeout, TimeUnit unit)方法来等待进程完成,其中timeout参数表示规定时间的长度,unit参数表示时间单位。如果进程在规定时间内完成,该方法将返回0;如果超过规定时间,该方法将抛出InterruptedException。
5.2.waitfor(long timeOut, TimeUnit time) When this method is executed, then it will placethe current execution process thread in the blocking-wait state unless the sub-process gets terminated or runs out of time. Let's take a look at the example: ...
ProcessBuilder processBuilder=newProcessBuilder("ps");processBuilder.redirectErrorStream(true);Process process=processBuilder.start(); processBuilder.start() 会立刻返回,不会待ps进程结束。所以Process提供waitFor方法,调用后线程阻塞,直到ps命令结束。但有一个问题,当命令的输出很多内容时,waitFor方法会一直卡着不返回...
之后发现在Process类中有一个waitFor()方法可以实现。如下: Process p =null; try { p = Runtime.getRuntime().exec("notepad.exe"); p.waitFor(); }catch (Exception e) { e.printStackTrace(); } System.out.println("我想被打印..."); ...
Process process = Runtime.getRuntime().exec("tasklist"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); process.waitFor(); 原文由 user590444 发布,翻译遵循 CC BY-SA 4.0 许可协议 javaruntime.exec ...