Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can check Runtime.exec(cmd) is completed or not

Tags:

java

how can check Runtime.exec(cmd) is completed or not?

It is running but how can I check command is executed or not in java program?

If I used process to check then it is blocking current thread. If I stopped running program then Runtime.exec(cmd) is executing. What should I do?

like image 511
jagannath Avatar asked Jun 24 '15 07:06

jagannath


People also ask

What does runtime exec do?

exec(String[] cmdarray, String[] envp) method executes the specified command and arguments in a separate process with the specified environment. This is a convenience method. An invocation of the form exec(cmdarray, envp) behaves in exactly the same way as the invocation exec(cmdarray, envp, null).

What is Runtime getRuntime in Java?

getRuntime() method returns the runtime object associated with the current Java application. Most of the methods of class Runtime are instance methods and must be invoked with respect to the current runtime object.

What is Runtime instance?

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method. An application cannot create its own instance of this class.

What is Runtime class in Java?

Runtime class is a subclass of Object class, can provide access to various information about the environment in which a program is running. The Java run-time environment creates a single instance of this class that is associated with a program.


1 Answers

The Process instance can help you manipulate the execution of your runtime through its InputStream and Outpustream.

The process instance has a waitFor() method that allows the current Thread to wait for the termination of the subprocess.

To control the completion of your process, you can also get the exitValue of your runtime, but this depends on what the process returns.

Here is a simple example of how to use the waitFor and get the process result (Note that this will block your current Thread until the process has ended).

public int runCommand(String command) throws IOException
{
    int returnValue = -1;
    try {
        Process process = Runtime.getRuntime().exec( command );
        process.waitFor();
        returnValue = process.exitValue();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return returnValue;
}
like image 152
Laurent B Avatar answered Oct 24 '22 10:10

Laurent B