6

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?

jagannath
  • 93
  • 2
  • 11
  • http://stackoverflow.com/questions/6873830/in-java-determine-if-a-process-created-using-runtime-environment-has-finished-ex – Ruchira Gayan Ranaweera Jun 24 '15 at 07:51
  • If I closed current thread then cmd is executing. – jagannath Jun 24 '15 at 08:32
  • What do you mean by closing current Thread ? – Laurent B Jun 24 '15 at 08:34
  • From what i understand (your last sentence is not very clear), you mean that if you don't use waitFor then your program exits. This does not mean that the runtime is not executed, simply that your java Thread did not wait for your command to complete and ended. – Laurent B Jun 24 '15 at 08:52
  • I have written Runtime.exec(cmd) in class "A" and now calling this class in class "B". If I stopped B class execution then class "A" is running otherwise it is not running. – jagannath Jun 24 '15 at 09:42

1 Answers1

14

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;
}
Laurent B
  • 2,200
  • 19
  • 29
  • Note that this will block your current Thread until the process has ended. I don't want to block current thread then what should I do? – jagannath Jun 24 '15 at 08:24
  • Then you should do the work in another Thread. Have a look at the java tutorial about concurrency. http://docs.oracle.com/javase/tutorial/essential/concurrency/ – Laurent B Jun 24 '15 at 08:33