【问题标题】:How do i terminate a process tree from Java?如何从 Java 终止进程树?
【发布时间】:2012-04-24 20:12:13
【问题描述】:

我在 Java 中使用 Runtime.getRuntime().exec() 命令来启动一个批处理文件,该批处理文件又为 windows 平台启动另一个进程。

javaw.exe(Process1)
 |___xyz.bat(Process2)
        |___javaw.exe(Process3)

Runtime.getRuntime().exec() 返回一个 Process 对象,它有一个 destroy 方法,但是当我使用 destroy() 时,它只杀死 xyz.bat 并使批处理文件的子进程悬空。

Java 中是否有一种干净的方式来销毁以根为根的批处理开始的进程树?

*我无法使用任何自定义库\摆脱批处理文件以绕过问题

【问题讨论】:

  • 我能问一下为什么没有自定义库要求吗?根据我的经验,这样的需求通常存在的理由很糟糕,并且可以通过解释需要库的原因进行协商(在这种情况下,Java 平台缺少必需的功能,即枚举父进程的子进程)。

标签: java windows batch-file cmd process


【解决方案1】:

您不能使用 JDK 终止 Windows 的进程树。您需要依赖 WinAPI。您将不得不求助于本机命令或 JNI 库,所有这些都依赖于平台并且比纯 Java 解决方案更复杂。

示例链接JNI Example

【讨论】:

  • 不幸的是,我不能使用任何外部或自定义库。但是,我可以更改批处理文件。有没有办法在 Process.destroy() 从 Java 发送的批处理中捕获术语信号?然后用它来杀死子进程?
  • 您可以使用批处理文件管理进程。请通过链接查看可管理的几个选项。 robvanderwoude.com/processes.php
  • 我不相信有任何方法可以让 Windows 批处理文件捕捉到这样的信号——Java 本机使用 TerminateProcess,它直接杀死进程而不先向它发送信号。此外,如果子进程正在运行,批处理文件必须等待它退出才能执行任何其他操作,Java 无法终止子进程。如果你想这样做,你将不得不使用外部库。
  • @Jules 我们不是试图从 .bat 文件中捕获进程的信号,而是使用可用的内置命令之一进行查询并终止进程,这是一种简单的方法提供的.bat文件可以修改,否则我们需要依赖JNA,这需要更多的努力。
  • 我对这个问题的理解是Process3是一个长时间运行的进程,必须在Process1的请求下终止。这给您建议的方法留下了两个问题:首先, Process1 将需要传达其意图以某种方式终止到批处理文件,这似乎有问题。然后批处理文件将需要终止 Process3,这很复杂,因为据我所知,它没有简单的方法来识别 Process3 的 PID(考虑到例如有多个实例的可能性相同的过程)。
【解决方案2】:

使用标准 Java API 无法做到这一点(请参阅文章末尾的编辑以获取更改此内容的更新)。您将需要一些不同种类的本机代码。使用 JNA,我使用了如下代码:

public class Win32Process
{
    WinNT.HANDLE handle;
    int pid;

    Win32Process (int pid) throws IOException
    {
        handle = Kernel32.INSTANCE.OpenProcess ( 
                0x0400| /* PROCESS_QUERY_INFORMATION */
                0x0800| /* PROCESS_SUSPEND_RESUME */
                0x0001| /* PROCESS_TERMINATE */
                0x00100000 /* SYNCHRONIZE */,
                false,
                pid);
        if (handle == null) 
            throw new IOException ("OpenProcess failed: " + 
                    Kernel32Util.formatMessageFromLastErrorCode (Kernel32.INSTANCE.GetLastError ()));
        this.pid = pid;
    }

    @Override
    protected void finalize () throws Throwable
    {
        Kernel32.INSTANCE.CloseHandle (handle);
    }

    public void terminate ()
    {
        Kernel32.INSTANCE.TerminateProcess (handle, 0);
    }

    public List<Win32Process> getChildren () throws IOException
    {
        ArrayList<Win32Process> result = new ArrayList<Win32Process> ();
        WinNT.HANDLE hSnap = KernelExtra.INSTANCE.CreateToolhelp32Snapshot (KernelExtra.TH32CS_SNAPPROCESS, new DWORD(0));
        KernelExtra.PROCESSENTRY32.ByReference ent = new KernelExtra.PROCESSENTRY32.ByReference ();
        if (!KernelExtra.INSTANCE.Process32First (hSnap, ent)) return result;
        do {
            if (ent.th32ParentProcessID.intValue () == pid) result.add (new Win32Process (ent.th32ProcessID.intValue ()));
        } while (KernelExtra.INSTANCE.Process32Next (hSnap, ent));
        Kernel32.INSTANCE.CloseHandle (hSnap);
        return result;
    }

}

此代码使用标准 JNA 库中未包含的以下 JNA 声明:

public interface KernelExtra extends StdCallLibrary {

    /**
     * Includes all heaps of the process specified in th32ProcessID in the snapshot. To enumerate the heaps, see
     * Heap32ListFirst.
     */
    WinDef.DWORD TH32CS_SNAPHEAPLIST = new WinDef.DWORD(0x00000001);

    /**
     * Includes all processes in the system in the snapshot. To enumerate the processes, see Process32First.
     */
    WinDef.DWORD TH32CS_SNAPPROCESS  = new WinDef.DWORD(0x00000002);

    /**
     * Includes all threads in the system in the snapshot. To enumerate the threads, see Thread32First.
     */
    WinDef.DWORD TH32CS_SNAPTHREAD   = new WinDef.DWORD(0x00000004);

    /**
     * Includes all modules of the process specified in th32ProcessID in the snapshot. To enumerate the modules, see
     * Module32First. If the function fails with ERROR_BAD_LENGTH, retry the function until it succeeds.
     */
    WinDef.DWORD TH32CS_SNAPMODULE   = new WinDef.DWORD(0x00000008);

    /**
     * Includes all 32-bit modules of the process specified in th32ProcessID in the snapshot when called from a 64-bit
     * process. This flag can be combined with TH32CS_SNAPMODULE or TH32CS_SNAPALL. If the function fails with
     * ERROR_BAD_LENGTH, retry the function until it succeeds.
     */
    WinDef.DWORD TH32CS_SNAPMODULE32 = new WinDef.DWORD(0x00000010);

    /**
     * Includes all processes and threads in the system, plus the heaps and modules of the process specified in th32ProcessID.
     */
    WinDef.DWORD TH32CS_SNAPALL      = new WinDef.DWORD((TH32CS_SNAPHEAPLIST.intValue() |
            TH32CS_SNAPPROCESS.intValue() | TH32CS_SNAPTHREAD.intValue() | TH32CS_SNAPMODULE.intValue()));

    /**
     * Indicates that the snapshot handle is to be inheritable.
     */
    WinDef.DWORD TH32CS_INHERIT      = new WinDef.DWORD(0x80000000);

    /**
     * Describes an entry from a list of the processes residing in the system address space when a snapshot was taken.
     */
    public static class PROCESSENTRY32 extends Structure {

        public static class ByReference extends PROCESSENTRY32 implements Structure.ByReference {
            public ByReference() {
            }

            public ByReference(Pointer memory) {
                super(memory);
            }
        }

        public PROCESSENTRY32() {
            dwSize = new WinDef.DWORD(size());
        }

        public PROCESSENTRY32(Pointer memory) {
            useMemory(memory);
            read();
        }

        /**
         * The size of the structure, in bytes. Before calling the Process32First function, set this member to
         * sizeof(PROCESSENTRY32). If you do not initialize dwSize, Process32First fails.
         */
        public WinDef.DWORD dwSize;

        /**
         * This member is no longer used and is always set to zero.
         */
        public WinDef.DWORD cntUsage;

        /**
         * The process identifier.
         */
        public WinDef.DWORD th32ProcessID;

        /**
         * This member is no longer used and is always set to zero.
         */
        public BaseTSD.ULONG_PTR th32DefaultHeapID;

        /**
         * This member is no longer used and is always set to zero.
         */
        public WinDef.DWORD th32ModuleID;

        /**
         * The number of execution threads started by the process.
         */
        public WinDef.DWORD cntThreads;

        /**
         * The identifier of the process that created this process (its parent process).
         */
        public WinDef.DWORD th32ParentProcessID;

        /**
         * The base priority of any threads created by this process.
         */
        public WinDef.LONG pcPriClassBase;

        /**
         * This member is no longer used, and is always set to zero.
         */
        public WinDef.DWORD dwFlags;

        /**
         * The name of the executable file for the process. To retrieve the full path to the executable file, call the
         * Module32First function and check the szExePath member of the MODULEENTRY32 structure that is returned.
         * However, if the calling process is a 32-bit process, you must call the QueryFullProcessImageName function to
         * retrieve the full path of the executable file for a 64-bit process.
         */
        public char[] szExeFile = new char[WinDef.MAX_PATH];
    }


    // the following methods are in kernel32.dll, but not declared there in the current version of Kernel32:

    /**
     * Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these processes.
     *  
     * @param dwFlags
     *   The portions of the system to be included in the snapshot.
     * 
     * @param th32ProcessID
     *   The process identifier of the process to be included in the snapshot. This parameter can be zero to indicate
     *   the current process. This parameter is used when the TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE,
     *   TH32CS_SNAPMODULE32, or TH32CS_SNAPALL value is specified. Otherwise, it is ignored and all processes are
     *   included in the snapshot.
     *
     *   If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last
     *   error code is ERROR_ACCESS_DENIED because their access restrictions prevent user-level code from opening them.
     *
     *   If the specified process is a 64-bit process and the caller is a 32-bit process, this function fails and the
     *   last error code is ERROR_PARTIAL_COPY (299).
     *
     * @return
     *   If the function succeeds, it returns an open handle to the specified snapshot.
     *
     *   If the function fails, it returns INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
     *   Possible error codes include ERROR_BAD_LENGTH.
     */
    public WinNT.HANDLE CreateToolhelp32Snapshot(WinDef.DWORD dwFlags, WinDef.DWORD th32ProcessID);

    /**
     * Retrieves information about the first process encountered in a system snapshot.
     *
     * @param hSnapshot A handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
     * @param lppe A pointer to a PROCESSENTRY32 structure. It contains process information such as the name of the
     *   executable file, the process identifier, and the process identifier of the parent process.
     * @return
     *   Returns TRUE if the first entry of the process list has been copied to the buffer or FALSE otherwise. The
     *   ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no processes exist or the snapshot
     *   does not contain process information.
     */
    public boolean Process32First(WinNT.HANDLE hSnapshot, KernelExtra.PROCESSENTRY32.ByReference lppe);

    /**
     * Retrieves information about the next process recorded in a system snapshot.
     *
     * @param hSnapshot A handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
     * @param lppe A pointer to a PROCESSENTRY32 structure.
     * @return
     *   Returns TRUE if the next entry of the process list has been copied to the buffer or FALSE otherwise. The
     *   ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no processes exist or the snapshot
     *   does not contain process information.
     */
    public boolean Process32Next(WinNT.HANDLE hSnapshot, KernelExtra.PROCESSENTRY32.ByReference lppe);


}

然后您可以使用“getChildren()”方法获取子列表,终止父节点,然后递归终止子节点。

我相信您可以使用反射来增加 java.lang.Process 的 PID(不过,我没有这样做;我转而使用 Win32 API 自己创建进程,以便对它有更多的控制权) .

所以把它放在一起,你需要这样的东西:

int pid = (some code to extract PID from the process you want to kill);
Win32Process process = new Win32Process(pid);
kill(process);

public void kill(Win32Process target) throws IOException
{
   List<Win32Process> children = target.getChildren ();
   target.terminateProcess ();
   for (Win32Process child : children) kill(child);
}

编辑

事实证明,Java API 的这一特殊缺陷正在 Java 9 中得到修复。请参阅 Java 9 文档的预览here(如果未加载正确的页面,您需要查看@987654326 @ 界面)。对于上述问题的要求,代码现在看起来像这样:

Process child = ...;
kill (child.toHandle());

public void kill (ProcessHandle handle)
{
    handle.descendants().forEach((child) -> kill(child));
    handle.destroy();
}

(请注意,这未经测试 - 我还没有切换到 Java 9,但我正在积极阅读它)

【讨论】:

  • “编辑”部分在 Java 11 上对我有用,尽管查看了所有 JNI 代码,但我几乎错过了它。既然 Java 11 目前是 LTS 版本,也许这段代码应该放在最前面。
  • 上述帖子中的 Java9 文档链接现在不可用,这里是更新的链接。 docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html
  • java.lang.ProcessHandle 方法看起来像干净的 Java。它也适用于 Linux。
【解决方案3】:

如果您控制子进程以及批处理文件,另一种解决方案是让子进程创建一个线程,打开一个 ServerSocket,监听到它的连接,然后调用 System.exit() 如果它会收到正确的密码。

如果您需要多个同时执行的实例,可能会出现复杂情况;到那时,您将需要某种方式为它们分配端口号。

【讨论】:

    【解决方案4】:

    这是另一种选择。使用这个 powershell 脚本来执行你的 bat 脚本。当你想杀死树时,终止你的 powershell 脚本的进程,它会自动在它的子进程上执行 taskkill。我让它调用 taskkill 两次,因为在某些情况下它不会在第一次尝试时进行。

    Param(
        [string]$path
    )
    
    $p = [Diagnostics.Process]::Start("$path").Id
    
    try {
        while($true) {
            sleep 100000
        }
    } finally {
        taskkill /pid $p
        taskkill /pid $p
    }
    

    【讨论】:

      【解决方案5】:

      使用 java 9,杀死主进程会杀死整个进程树。你可以这样做:

      Process ptree = Runtime.getRuntime().exec("cmd.exe","/c","xyz.bat");
      // wait logic
      ptree.destroy();
      

      请查看此blog 并查看处理流程树示例。

      【讨论】:

        【解决方案6】:

        您无法使用 Java 8 或更低版本的标准 Java API 来做到这一点。

        方法一

        如果你有 Java 9 或更高版本,你可以使用ProcessHandle

        方法二

        在 Java 中将 taskkill 与 /t 和 /f 标志与 Runtime.getRuntime().exec() 或 ProcessBuilder 类一起使用。

        /f --> 强制杀死 /t --> 杀死该进程生成的所有子进程。

        ProcessBuilder pb1 = new ProcessBuilder("cmd.exe","/c","taskkill /f /t /pid "+p.pid());
        Process p1 = pb1.start();
        

        详细分析

        我曾使用流程构建器在我的 Java 代码中完成此操作。

        我已经复制了问题陈述。 这是一个示例批处理文件,它在 windows 中启动另一个 Powershell 进程以每秒打印从 1 到 20 的计数器,这是子进程:

        @echo off
        echo starting
        powershell -command " for ($count=1;$count -le 20;$count++) { Start-Sleep 1; Write-Output $count }"
        echo success
        

        ps:您需要将 InputStream 重定向到 stdout 以获得终端上的输出。

        使用process 对象的destroy() 方法只会杀死该进程,而不是子/孙进程。

        你可以在终端上运行tasklist并定位powershell.exe来比较你运行java程序之前和之后的子进程是否还在运行。

        要与父进程一起杀死子进程,请使用ProcessBuilder 启动一个新进程,如下所示,其中p 是您要摆脱的进程:

        ProcessBuilder pb1 = new ProcessBuilder("cmd.exe","/c","taskkill /f /t /pid "+p.pid());
        Process p1 = pb1.start();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-06-03
          • 2010-11-13
          • 1970-01-01
          • 1970-01-01
          • 2010-10-06
          • 2018-09-30
          • 2010-11-26
          • 1970-01-01
          相关资源
          最近更新 更多