簡體   English   中英

如何終止進程樹?

[英]How do I terminate a process tree?

我正在使用Runtime.getRuntime().exec()命令啟動一個批處理文件,該批處理文件又為 windows 平台啟動另一個進程。

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

Runtime.getRuntime().exec()返回一個Process object ,它有一個 destroy 方法,但是當我使用destroy()時,它只殺死xyz.bat並使批處理文件的子進程懸空。

是否有一種干凈的方法來銷毀以 root 身份開始的批處理過程樹?

作為記錄,我不能使用任何自定義庫來擺脫批處理文件來繞過這個問題。

使用標准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文檔預覽(如果沒有加載正確的頁面,則需要查看java.lang.ProcessHandle接口) 。 對於上述問題的要求,代碼現在看起來像這樣:

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

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

(請注意,這未經過測試 - 我還沒有切換到Java 9,但我正在積極閱讀它)

如果您控制子進程以及批處理文件,另一種解決方案是讓子進程創建一個線程,打開一個ServerSocket,監聽它的連接,如果收到一個,則調用System.exit()正確的密碼就可以了。

如果您需要多個同時實例,可能會出現並發症; 那時你需要一些方法來為它們分配端口號。

您不能使用 Java 8 或更低版本的標准 Java API 來執行此操作。

方法一

如果你有Java 9以上,你可以使用ProcessHandle

方法二

Runtime.getRuntime().exec() ProcessBuilder taskkill/t/f標志一起使用。

/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 以在終端上獲取 output。

使用process object 的destroy()方法只會殺死該進程,而不會殺死子/孫進程。

可以在終端運行tasklist ,找到powershell.exe ,對比運行java程序前后,子進程是否還在運行。

要與父進程一起終止子進程,請使用ProcessBuilder啟動一個新進程,如下所示,其中p是您要擺脫的進程:

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

您無法使用JDK終止Windows的進程樹。 您需要依賴WinAPI。您將不得不求助於本機命令或JNI庫,所有這些都是依賴於平台的,並且比純Java解決方案更復雜。

示例鏈接JNI示例

這是另一種選擇。 使用此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
}

使用java 9,查殺主進程會終止整個進程樹。 你可以這樣做:

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

請查看此博客並查看處理樹處理示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM