简体   繁体   English

如何使用SIGKILL杀死java中的Linux进程Process.destroy()执行SIGTERM

[英]how can I kill a Linux process in java with SIGKILL Process.destroy() does SIGTERM

在Linux上,当我在java.lang.Process对象上运行destroy函数(这是真正的类型java.lang.UNIXProcess)时,它会发送一个SIGTERM信号进行处理,有没有办法用SIGKILL来杀死它?

Not using pure Java. 不使用纯Java。

Your simplest alternative is to use Runtime.exec() to run a kill -9 <pid> command as an external process. 最简单的替代方法是使用Runtime.exec()作为外部进程运行kill -9 <pid>命令。

Unfortunately, it is not that simple to get hold of the PID. 不幸的是,掌握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. 您将需要使用反射黑魔术来访问private int pid字段,或者使用ps命令的输出。

UPDATE - actually, there is another way. 更新 - 实际上,还有另一种方式。 Create a little utility (C program, shell script, whatever) that will run the real external application. 创建一个运行真实外部应用程序的小实用程序(C程序,shell脚本等)。 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. 对该实用程序进行编码,使其记住子进程的PID,并为SIGTERM设置SIGKILL子进程的信号处理程序。

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

You can also get the pid this way: 你也可以这样得到pid:

public static int getPID() {
  String tmp = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
  tmp = tmp.split("@")[0];
  return Integer.valueOf(tmp);
}

如果您知道进程名称,则可以使用pkill

Runtime.getRuntime().exec("pkill firefox").waitFor();

Since Java 1.8 自Java 1.8以来

you can call the method destroyForcibly() , which calls the destroy() method by default, but according to the Java docs, all sub-processes returned by ProcessBuilder or Runtime.exec() implement this method. 你可以调用destroyForcibly()方法,它默认调用destroy()方法,但是根据Java文档, ProcessBuilderRuntime.exec()返回的所有子进程都实现了这个方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM