Java,在Windows上检查是否有任何进程ID正在运行

6

在Windows中,从Java程序中检查进程是否存在是可能的。

我有它可能的PID,我想知道它是否仍在运行。


请查看以下链接:https://dev59.com/YXvaa4cB1Zd3GeqPJu8K#26423642 - itaifrenkel
4个回答

4

如何使用Java在Windows上检查进程是否正在运行:

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>

第二列为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>

当你得到一个响应时,意味着该进程ID正在运行。

如果你查询的进程ID不存在,你会得到如下结果:

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

一个Java函数可以自动完成上述操作

这个函数只能在拥有可用tasklist的Windows系统上运行。

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

2
看看这个能不能帮助到你:

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

该帖子解释了如何在Windows机器上获取所有正在运行的PID:您需要将cmd调用的输出与您的PID进行比较,而不是打印它。
如果您在类Unix系统上,则必须使用ps而不是cmd
从Java代码调用系统命令并不是一个非常可移植的解决方案; 同样,进程的实现因操作系统而异。

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;
    }
}

-1
  1. 从Maven将JNA导入到您的项目中
  2. Maven更新后,您可以使用以下代码:

int myPid = Kernel32.INSTANCE.GetCurrentProcessId();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接