论坛首页 Java企业应用论坛

ps.waitFor() 无法返回的解决方法

浏览 21358 次
该帖已经被评为精华帖
作者 正文
   发表时间:2003-10-12  
直接调用 Process 类型对象的 waitFor() 方法的时候当前线程会被 block 掉,解决办法是调用一个用户化的 doWaitFor() 方法。即把以前使用的 ps.waitFor() 替换为 doWaitFor(ps)。
public static int doWaitFor(Process p); {
    int exitValue = -1; // returned to caller when p is finished
    try {

        InputStream in = p.getInputStream();;
        InputStream err = p.getErrorStream();;
        boolean finished = false; // Set to true when p is finished

        while(!finished); {
            try {
                while( in.available(); > 0); {
                    // Print the output of our system call
                    Character c = new Character( (char); in.read(););;
                    System.out.print( c);;
                }
                while( err.available(); > 0); {
                    // Print the output of our system call
                    Character c = new Character( (char); err.read(););;
                    System.out.print( c);;
                }

                // Ask the process for its exitValue. If the process
                // is not finished, an IllegalThreadStateException
                // is thrown. If it is finished, we fall through and
                // the variable finished is set to true.
                exitValue = p.exitValue();;
                finished = true;
            }
            catch (IllegalThreadStateException e); {
                // Process is not finished yet;
                // Sleep a little to save on CPU cycles
                Thread.currentThread();.sleep(500);;
            }
        }
    }
    catch (Exception e); {
        // unexpected exception! print it out for debugging...
        System.err.println( "doWaitFor();: unexpected exception - " +
        e.getMessage(););;
    }

    // return completion status to caller
    return exitValue;
}

这个问题不能说是 JVM 的 Bug,具体的原因请看:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps_p.html
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics