Friday 11 October 2013

The problem with Process.waitFor() method

I have recently experienced a strange problem while calling Lame to do a music file conversion. For some audio files, my application just hangs without any output.The code is shown as follows:

Runtime rt = Runtime.getRuntime();
Process p = rt.exec(commands);
p.waitFor();
int exitVal = p.exitValue();

Eventually I found that problem was caused by a process dead lock. In short, Lame produces lots output to stderr/stdout but the buffer size is fixed, therefore, Lame expects my application to consume/clear the buffer before it can continue processing. However, when I called p.waitFor(), my application is expecting Lame to exit. In such a situation, a dead lock is happending! To fixed the problem:

Runtime rt = Runtime.getRuntime();
Process p = rt.exec(commands);
InputStream stderr = p.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null)
    logger.info(line);

int exitVal = p.waitFor();

For more information, please see this post, I know it is a post in 2000, but it still applies!

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1





No comments:

Post a Comment