0

How can I get process state, that is it running or completed.

I am creating new process through:

processBuilder();
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Usama Nadeem
  • 89
  • 1
  • 4
  • 10
  • 1
    *"Any help will be appreciated. thanks:"* A '?' added to the question would be more likely to elicit help than adding such noise. BTW - what 'state' are you referring to? For 'completion' look to [`Process.waitFor()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#waitFor%28%29) & [`exitValue()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#exitValue%28%29). – Andrew Thompson Dec 25 '13 at 12:15
  • 1
    May be [that](http://stackoverflow.com/a/11510642/2894369) can help you. – alex2410 Dec 25 '13 at 12:16
  • 1
    Java comes with a very comprehensive documentation, check out the [Process](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html) and [ProcessBuilder](http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html) objects. If you still have an issue, show that you've read the documentation and improve your question. And FYI: its `ProcessBuilder` not `processBuilder`. – initramfs Dec 25 '13 at 12:18
  • You really should accept an answer. As it is, this near duplicate question should be closed. Please be a little more polite. – user3125280 Dec 26 '13 at 12:24

2 Answers2

1
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Process p = pb.start();

followed by

p.exitValue() //throws an IllegalThreadStateException - if the subprocess represented by                //this Process object has not yet terminated.

A shameless copy and paste job from the documentation, btw. Always a good place to start.

user3125280
  • 2,779
  • 1
  • 14
  • 23
1

There is no direct method available that can provide you the state of the process if you use use the waitFor then your current thread will wait until the process terminates.
So you can use exitValue function wrapped in function something like this,

public static boolean isProcessRunning(Process process) 
{
    try 
    {
        process.exitValue();
        return false;
    } 
    catch(IllegalThreadStateException e) 
    {
        return true;
    }
}

And then you can continue doing other work and call above method to check the state as and when needed.

Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58