简体   繁体   中英

How to know whether command executed using Runtime.exec() is giving some output or is only waiting and not giving any output?

I am trying to run an accurev command using Java Runtime exec (as described in code below). Since I have a network problem so when the login command is executed the command keeps on waiting for the response and doesn't time out. So how should I be able handle this error.

private static void accurevLogin() throws IOException {
    Runtime runTime = Runtime.getRuntime();
    String userName = prop.getProperty("UserName");
    String password = prop.getProperty("Password");
    String command = (new StringBuilder("accurev login ")).append(userName).append(" ").append(password).toString();
    Process ps = null;
    try {
        ps = runTime.exec(command);
    } catch (IOException e) {
        System.out.println("Command Execution Error!");
    }
    /* Error handling Code */
    System.out.println("ACCUREV LOGGED IN");
}

When I use

BufferedReader input = new BufferedReader(new InputStreamReader(ps.getInputStream()));

input.readline in the loop will keep on running and I am not able to check the output.

The best way would be to use a timeout option of the accurev command, if available.

If there is no such option, you should execute it in a seperate Java thread and abort programatically after some timeout of your choosing.

Here is an example with a simple sleep command:

Thread thread = new Thread() {
    public void run() {
        try {
            Process proc = Runtime.getRuntime().exec("sleep 5");
        } catch (IOException e) {
        e.printStackTrace();
        }
    }
};
thread.start();  //start thread in background
synchronized (thread) {
    try {
        thread.wait(1000L);  //your timeout
        if (thread.isAlive()) {
            System.out.println("interrupting");
            thread.interrupt();  //interrupt the thread
        }
    } catch (Exception e) {
        System.out.println("interrupted");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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