繁体   English   中英

Java Runtime.exec()挂起

[英]Java Runtime.exec() hanging

每当执行以下代码时,我就会进入Defunct僵尸进程。 有人可以帮我解决这个问题。

  private static boolean executeCommand(String command)
        throws ClientException, IOException, InterruptedException {

    int exitVal = 1; // 0 is success, so we default to a nonzero.
    Process proc = null;
    try{
    Runtime rt = Runtime.getRuntime();
    proc = rt.exec(command);

    //Below lines are required to flush out the streams. else the process will hang.
    ReadStream s1 = new ReadStream("stdin", proc.getInputStream ());
    ReadStream s2 = new ReadStream("stderr", proc.getErrorStream ());
    s1.start ();
    s2.start ();        

    exitVal = proc.waitFor();

    if (exitVal == 0) {
        return true;
    } else {
        throw new ClientException("103", "" + command + " failed.");
    }
    }finally{
        if(proc  != null){
            proc.destroy();
        }
    }

}

我在单独的线程中清除所有流。

这是我的ReadStream类

 public class ReadStream implements Runnable {

private static Logger logger = Logger.getLogger(ReadStream.class);

String name;
InputStream is;
Thread thread;

public ReadStream(String name, InputStream is) {
    this.name = name;
    this.is = is;
}

public void start() {
    thread = new Thread(this);
    thread.start();
}

public void run() {
    try {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        while (true) {
            String s = br.readLine();
            if (s == null)
                break;
            logger.info("[" + name + "] " + s);
        }
        is.close();
    } catch (Exception ex) {
        logger.error("Problem reading stream " + name + "... :" + ex);

    }
}

}

我不认为这是问题所在,但尝试将运行方法更改为:

try {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        do {
            String s = br.readLine();
            if (s != null)
              logger.info("[" + name + "] " + s);
        } while (s != null);
        is.close();
    } catch (Exception ex) {
        logger.error("Problem reading stream " + name + "... :" + ex);

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM