2009年7月29日水曜日

Processの問題

どうもJavaでProcessを使って別プロセス処理をする場合,InputStreamとErrorStreamをうまく処理してあげないとデッドロックになるらしい.

process = rt.exec(command);
exitValue = process.waitFor();

このとき,commandから大量の出力が出るとデッドロック状態になる.
InputStreamとErrorStreamはStreamなのである程度以上の文字列を確保出来ないためらしい.
そのため,

private void exec(String command, StringBuffer stdOutput){
process = rt.exec(command);
readOutput(stdOutput, process.getInputStream());
exitValue = process.waitFor();
}

private void readOutput(final StringBuffer buf, final InputStream is) {
Runnable runner = new Runnable(){
@Override
public void run() {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
try{
while((line = br.readLine()) != null){
buf.append(line);
buf.append("\n");
System.out.println(">"+line);
}
}catch(IOException e){

}
}
};

Thread th = new Thread(runner);
th.start();
}

とやると比較的うまくいく.

0 件のコメント: