In Linux when I run the destroy function on java.lang.Process object (Which is true typed java.lang.UNIXProcess ) it sends a SIGTERM signal to process, is there a way to kill it with SIGKILL?
views:
274answers:
2
+3
A:
Not using pure Java.
Your simplest alternative is to use Runtime.exec()
to run a kill -9 <pid>
command as an external process.
Unfortunately, it is not that simple to get hold of the PID. You will either need to use reflection black-magic to access the private int pid
field, or mess around with the output from the ps
command.
UPDATE - actually, there is another way. Create a little utility (C program, shell script, whatever) that will run the real external application. Code the utility so that it remembers the PID of the child process, and sets up a signal handler for SIGTERM that will SIGKILL the child process.
Stephen C
2010-06-01 14:09:37
I can do it like this or in JNI , although I am not eager to do it this way, how do you know the pid of the process you want to kill?
ekeren
2010-06-01 14:12:15
First thanks for these replies. reflection and JNI/exec are my last resort, I wonder if someone can find a more elegant way to do this.
ekeren
2010-06-01 14:20:38
I also tough about a wrapper executioner, actually my boss tough about it:), So I understand that there is no straight forward way of doing this that you know of.
ekeren
2010-06-01 14:25:18
@ekeren - Correct. I suppose you could download the OpenJDK sources, modify them and build a custom JVM ... but that's an even worse alternative.
Stephen C
2010-06-01 14:34:47
A:
Stehpen his answer is correct. I wrote what he said:
public static int getUnixPID(Process process) throws Exception
{
System.out.println(process.getClass().getName());
if (process.getClass().getName().equals("java.lang.UNIXProcess"))
{
Class cl = process.getClass();
Field field = cl.getDeclaredField("pid");
field.setAccessible(true);
Object pidObject = field.get(process);
return (Integer) pidObject;
} else
{
throw new IllegalArgumentException("Needs to be a UNIXProcess");
}
}
public static int killUnixProcess(Process process) throws Exception
{
int pid = getUnixPID(process);
return Runtime.getRuntime().exec("kill " + pid).waitFor();
}
Martijn Courteaux
2010-06-01 15:48:55