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?
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).
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With