Skip to main content

Command Palette

Search for a command to run...

Java Runtime.exec取stderr阻塞

Published
•1 min read•View as Markdown

原因:

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
翻译:
一些平台只为标准输入输出提供有限的缓存。错误的写子进程的输入流或者错误的都子进程的输出流都有可能造成子进程的阻塞,甚至是死锁。

解决方法:

把读取stderr及stdout的操用放到单独的线程中,示例代码:

```java
Process process = Runtime.getRuntime().exec(this.command, envs);
 //System.out.println("-------------------------------------");
 BufferedReader ebr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
 Thread eThread = new Thread(() -> 
 try 
 String eline;
 while (null != (eline = ebr.readLine())) 
 System.out.println("[Error]" + eline);

 ebr.close();
 catch (Exception e) 
 e.printStackTrace();

 );
 eThread.start();
 //System.out.println("-------------------------------------");
 BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
 Thread oThread = new Thread(() -> 
 try 
 String line;
 while (null != (line = br.readLine())) 
 System.out.println(line);

 br.close();
 br.close();
 catch (Exception e) 
 e.printStackTrace();

 );
 oThread.start();
 process.waitFor();
 ```

More from this blog

解决QWidget用winId获取HWND而导致Qt程序无事件消息的问题

问题原因: 当对一个QWidget调用winId时,默认情况下,Qt会对该窗口进行Native化,从而导致如鼠标等事件被其它原生窗口接管,表现出来的现像就是窗口不响应任何事件 解决思路: 防止Qt窗口Native化 解决办法: 第一步,在创建QApplication对象之前设置: QApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); //注意:Qt::AA_NativeWindows受环境变量 QT_USE_NATI...

Jul 7, 20251 min read
雷

雷的部落格威力缩小版

30 posts

雷的部落格威力缩小版