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.
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();
}
}
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