如何使用javas Process.waitFor()? [英] How to use javas Process.waitFor()?

查看:170
本文介绍了如何使用javas Process.waitFor()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Java运行命令行命令,快速的健全性检查让我意识到我遇到麻烦的原因是我无法获得 pr.waitFor()请致电以下工作。这个程序在不到30秒后结束,并且在foo:之后不打印任何内容。我预计它需要超过30秒并在foo:之后打印一个随机数。我究竟做错了什么?

I am trying to run command line commands from Java and a quick sanity check made me realize that the reason I am having trouble is that I can't get the pr.waitFor() call below to work. This programs ends in less than 30s and prints nothing after "foo:". I expected it to take just over 30 s and print a random number after "foo:". What am I doing wrong?

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Sample {

    public static void main(String[] args) throws Exception {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("sleep 32; echo $RANDOM");
        pr.waitFor();

        BufferedReader input = new BufferedReader(
                                   new InputStreamReader(pr.getInputStream()));
        String line=null;

        StringBuilder s = new StringBuilder();
        while((line=input.readLine()) != null) {
            System.out.println(s);
            s.append(line);
        }
        System.out.println("foo: " + s.toString());
    }
}


推荐答案

你应该尝试这个:

Process pr = rt.exec(new String[]{ "bash","-c", "sleep 32; echo $RANDOM" });

这将启动一个shell进程,然后在shell中运行你的命令。在命令完成之后,shell才会返回。

This launches a shell process and then within the shell runs your commands. The shell doesn't return till AFTER the commands have completed.

请告诉我这是否适合您。

Let me know if that works for you.

这篇关于如何使用javas Process.waitFor()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆