6

WindowsでJavaからプロセスの存在を確認することはできますか?

PID の可能性があります。まだ実行されているかどうかを知りたいです。

4

4 に答える 4

4

Windows で Java を使用して pid が実行されているかどうかを確認する方法:

Windows タスクリスト コマンド:

DOS コマンドtasklistは、実行中のプロセスに関する出力を表示します。

C:\Documents and Settings\eric>tasklist

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
System Idle Process            0 Console                 0         28 K
System                         4 Console                 0        244 K
smss.exe                     856 Console                 0        436 K
csrss.exe                    908 Console                 0      6,556 K
winlogon.exe                 932 Console                 0      4,092 K
....
cmd.exe                     3012 Console                 0      2,860 K
tasklist.exe                5888 Console                 0      5,008 K

C:\Documents and Settings\eric>

2 番目の列は PID です

tasklist特定の PID に関する情報を取得するために使用できます。

tasklist /FI "PID eq 1300"

プリント:

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
mysqld.exe                  1300 Console                 0     17,456 K

C:\Documents and Settings\eric>

応答は、PID が実行中であることを意味します。

存在しない PID を照会すると、次のようになります。

C:\Documents and Settings\eric>tasklist /FI "PID eq 1301"
INFO: No tasks running with the specified criteria.
C:\Documents and Settings\eric>

Java関数は上記を自動的に行うことができます

この機能は、利用可能な Windows システムでのみ機能しtasklistます。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class IsPidRunningTest {

    public static void main(String[] args) {

        //this function prints all running processes
        showAllProcessesRunningOnWindows();

        //this prints whether or not processID 1300 is running
        System.out.println("is PID 1300 running? " + 
            isProcessIdRunningOnWindows(1300));

    }

    /**
     * Queries {@code tasklist} if the process ID {@code pid} is running.
     * @param pid the PID to check
     * @return {@code true} if the PID is running, {@code false} otherwise
     */
    public static boolean isProcessIdRunningOnWindows(int pid){
        try {
            Runtime runtime = Runtime.getRuntime();
            String cmds[] = {"cmd", "/c", "tasklist /FI \"PID eq " + pid + "\""};
            Process proc = runtime.exec(cmds);

            InputStream inputstream = proc.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            String line;
            while ((line = bufferedreader.readLine()) != null) {
                //Search the PID matched lines single line for the sequence: " 1300 "
                //if you find it, then the PID is still running.
                if (line.contains(" " + pid + " ")){
                    return true;
                }
            }

            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("Cannot query the tasklist for some reason.");
            System.exit(0);
        }

        return false;

    }

    /**
     * Prints the output of {@code tasklist} including PIDs.
     */
    public static void showAllProcessesRunningOnWindows(){
        try {
            Runtime runtime = Runtime.getRuntime();
            String cmds[] = {"cmd", "/c", "tasklist"};
            Process proc = runtime.exec(cmds);
            InputStream inputstream = proc.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            String line;
            while ((line = bufferedreader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("Cannot query the tasklist for some reason.");
        }
    }
}

上記の Java コードは、実行中のすべてのプロセスのリストを出力してから、以下を出力します。

is PID 1300 running? true
于 2013-08-01T20:42:48.050 に答える
2

コード:

boolean isStillAllive(String pidStr) {
    String OS = System.getProperty("os.name").toLowerCase();
    String command = null;
    if (OS.indexOf("win") >= 0) {
        log.debug("Check alive Windows mode. Pid: [{}]", pidStr);
        command = "cmd /c tasklist /FI \"PID eq " + pidStr + "\"";
        return isProcessIdRunning(pidStr, command);
    } else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0) {
        log.debug("Check alive Linux/Unix mode. Pid: [{}]", pidStr);
        command = "ps -p " + pidStr;
        return isProcessIdRunning(pidStr, command);
    }
    log.debug("Default Check alive for Pid: [{}] is false", pidStr);
    return false;
}


boolean isProcessIdRunning(String pid, String command) {
    log.debug("Command [{}]",command );
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec(command);

        InputStreamReader isReader = new InputStreamReader(pr.getInputStream());
        BufferedReader bReader = new BufferedReader(isReader);
        String strLine = null;
        while ((strLine= bReader.readLine()) != null) {
            if (strLine.contains(" " + pid + " ")) {
                return true;
            }
        }

        return false;
    } catch (Exception ex) {
        log.warn("Got exception using system command [{}].", command, ex);
        return true;
    }
}
于 2017-01-05T16:11:22.570 に答える
2

これが役立つかどうかを確認してください:

http://blogs.oracle.com/vaibhav/entry/listing_java_process_from_java

その投稿では、Windows マシンで実行されているすべての PID を取得する方法について説明していcmdます。呼び出しの出力を印刷する代わりに、PID と比較する必要があります。

Unix ライクなシステムを使用している場合は、ps代わりにwith を使用する必要がありますcmd

Java コードからシステム コマンドを呼び出すことは、移植性の高いソリューションではありません。繰り返しになりますが、プロセスの実装はオペレーティング システムによって異なります。

于 2010-03-28T18:39:16.820 に答える