16

私はJavaでRuntime.getRuntime()。exec()コマンドを使用してバッチファイルを開始し、それがWindowsプラットフォーム用の別のプロセスを開始します。

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

Runtime.getRuntime()。exec()は、destroyメソッドを持つProcessオブジェクトを返しますが、destroy()を使用すると、xyz.batのみが強制終了され、バッチファイルのサブプロセスがぶら下がったままになります。

ルートとしてのバッチプロセスで始まるプロセスツリーを破棄するためのクリーンな方法はJavaにありますか?

*カスタムライブラリを使用できません\問題を回避するためにバッチファイルを削除します

4

6 に答える 6

21

これは、標準の 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に切り替えていませんが、積極的に読んでいます)

于 2012-04-12T13:30:33.473 に答える
1

バッチ ファイルだけでなく子プロセスも制御する場合の別の解決策は、子プロセスにスレッドを作成させ、ServerSocket を開き、それへの接続をリッスンし、System.exit() を受け取った場合は System.exit() を呼び出すことです。その上の正しいパスワード。

複数の同時インスタンスが必要な場合は、複雑になる可能性があります。その時点で、ポート番号をそれらに割り当てる何らかの方法が必要になります。

于 2012-04-12T13:47:02.417 に答える
1

Java 8 以下の標準 Java API では実行できません。

方法 1

Java 9 以降を使用している場合は、ProcessHandleを使用できます。

方法 2

Java のまたはクラスtaskkill/tand/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コード内でプロセスビルダーを使用していました。

問題文を再現しました。Powershellこれは、 Windows で別のプロセスを開始して毎秒 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 にリダイレクトする必要があります。

destroy()オブジェクトのメソッドを使用するprocessと、そのプロセスのみが強制終了され、子/孫プロセスは強制終了されません。

tasklist端末で実行powershell.exeし、java プログラムを実行する前後を比較して、子プロセスがまだ実行されていることを確認できます。

親プロセスと一緒に子プロセスを強制終了するには、次のように使用して新しいプロセスを開始ProcessBuilderします。ここpで、削除するプロセスは次のとおりです。

ProcessBuilder pb1 = new ProcessBuilder("cmd.exe","/c","taskkill /f /t /pid "+p.pid());
Process p1 = pb1.start();
于 2021-07-13T08:30:09.133 に答える
0

ここに別のオプションがあります。この powershell スクリプトを使用して、bat スクリプトを実行します。ツリーを強制終了する場合は、powershell スクリプトのプロセスを終了すると、そのサブプロセスで taskkill が自動的に実行されます。場合によっては最初の試行が行われないため、taskkill を 2 回呼び出しています。

Param(
    [string]$path
)

$p = [Diagnostics.Process]::Start("$path").Id

try {
    while($true) {
        sleep 100000
    }
} finally {
    taskkill /pid $p
    taskkill /pid $p
}
于 2013-10-29T02:15:35.387 に答える
0

JDK を使用して Windows のプロセス ツリーを強制終了することはできません。WinAPI に頼る必要があります。ネイティブ コマンドまたは JNI ライブラリに頼る必要があります。これらはすべてプラットフォームに依存し、純粋な Java ソリューションよりも複雑です。

サンプル リンクJNI の例

于 2012-04-12T13:17:43.423 に答える