主进程调用Process.waitfor后已挂起。当前子进程和主进程之间的缓冲区塞满后,子进程不能继续写数据,然后也会挂起。
需要获取Process.getInputStream和Process.getErrorStream并处理。
// 处理子进程输出的线程,防止死锁 static class StreamHandler extends Thread { private InputStream in; public StreamHandler(InputStream in) { this.in = in; } public void run() { try { BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (Exception e) { System.out.println(e.getMessage()); } } } ProcessBuilder pb = new ProcessBuilder(); // 添加命令 pb.command(cmd); // 重定向错误输出,将错误输出合并到inputStream pb.redirectErrorStream(true); // 启动子进程 Process p = pb.start(); // 启动协助进程的子线程,将Process的inputStream输出,防止死锁 new StreamHandler(p.getInputStream()).start(); // 开始执行 int w = p.waitFor(); p.destroy();
原文地址:https://www.cnblogs.com/guofx/p/11558609.html
时间: 2024-10-23 02:32:40