![](/img/trans.png)
[英]Process.waitFor hangs even though stdout and stderr get read
[英]Process is hanging in java, waitFor() takes forever even though I've read (Input/Error)Stream
我在用Java運行多個進程時遇到麻煩。
我有一個循環,從向量cmds
運行進程,它當前運行第一個進程,然后第二個掛起。
ProcessBuilder proc = null;
for (String cmd:cmds){
proc = new ProcessBuilder(cmd.split("\\s"));
Process p = proc.start();
//Handle streams
//in
Scanner stdin = new Scanner(p.getInputStream());
while(stdin.hasNextLine()){
System.out.println(stdin.nextLine());
}
//err
Scanner stderr = new Scanner(p.getErrorStream());
while(stderr.hasNextLine()){
System.out.println(stderr.nextLine());
}
//wait
p.waitFor();
}
正如我從每個進程的InputStream和ErrorStream中讀取的那樣, 此答案顯然對我不起作用。 我有什么誤會?
我怎樣才能解決這個問題?
注意:我刪除了try塊,因為它對本示例代碼沒有太大幫助
編輯
proc = new ProcessBuilder(cur_string.split("\\s"));
proc. redirectErrorStream(true);
final Process p = proc.start();//Runtime.getRuntime().exec(cur_string);
//Handle streams
//in
new Thread(new Runnable(){
public void run(){
Scanner stdin = new Scanner(p.getInputStream());
while(stdin.hasNextLine()){
System.out.println(stdin.nextLine());
}
stdin.close();
}
}).start();
//wait
p.waitFor();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.