Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a process which is started by child thread?

Tags:

java

scope

Code:

main function{

Thread t =new Thread(){
     public void run(){
         Process p= Runtime.getRuntime().exec(my_CMD);
     }
};
t.start();
 //Now here, I want to kill(or destroy) the process p.

How can I do this in Java? If I make it as a class field as in

main function{
Process p;
Thread t =new Thread(){
     public void run(){
         p= Runtime.getRuntime().exec(my_CMD);
     }
};
t.start();
 //Now here, I want to kill(or destroy) the process p.

Since it is in a thread, it asks me to make the Process P as final. If I make that final, I cant assign value here. p= Runtime.getRuntime().exec(my_CMD); . plz help.

like image 901
shriguru nayak Avatar asked Oct 21 '22 04:10

shriguru nayak


1 Answers

The Process API already has a solution for this. What happened when you tried calling destroy() on the process? Of course assuming that you've changed the above code and have declared your Process variable, p, as a class field.

As an aside, you should avoid using Runtime.getRuntime().exec(...) to get your Process but rather should use a ProcessBuilder. Also, don't extend Thread when Runnable can be implemented.

class Foo {
  private Process p;

  Runnable runnable = new Runnable() {
    public void run() {
      ProcessBuilder pBuilder = new ProcessBuilder(...);  // fill in ...!
      // swallow or use the process's Streams!
      p = pBuilder.start();
    }
  }

  public Foo() {
    new Thread(runnable).start();
  }
}
like image 197
Hovercraft Full Of Eels Avatar answered Nov 01 '22 12:11

Hovercraft Full Of Eels