首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Runtime.exec()挂起

Java Runtime.exec()挂起
EN

Stack Overflow用户
提问于 2013-02-04 18:38:05
回答 1查看 455关注 0票数 0

每当执行下面的代码时,我都会进入已失效的僵尸进程。有人能帮我解决这个问题吗?

代码语言:javascript
复制
  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类

代码语言:javascript
复制
 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);

    }
}

}

EN

回答 1

Stack Overflow用户

发布于 2013-02-04 20:25:11

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

代码语言:javascript
复制
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);

    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14684937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档