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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2533984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:11:53  来源:igfitidea点击:

Java, Checking if any process ID is currently running on Windows

javawindowspid

提问by Roman

Is it possible to check the existence of process from Java in Windows.

是否可以在 Windows 中检查 Java 进程的存在。

I have its possible PID, I want to know if it is still running or not.

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

采纳答案by Silvio Donnini

See if this can help:

看看这是否有帮助:

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

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

That post explains how to get all PIDs running on a Windows machine: you'd have to compare the output of the cmdcall with your PID, instead of printing it.

那篇文章解释了如何让所有 PID 在 Windows 机器上运行:您必须将cmd调用的输出与您的 PID进行比较,而不是打印它。

If you're on Unix-like systems you'd have to use with psinstead of cmd

如果您在类 Unix 系统上,则必须使用 withps而不是cmd

Calling system commands from your java code is not a very portable solution; then again, the implementation of processes varies among operating systems.

从 Java 代码调用系统命令不是一个非常便携的解决方案;再说一次,进程的实现因操作系统而异。

回答by Eric Leschinski

How to check if a pid is running on Windows with Java:

如何使用 Java 检查 pid 是否在 Windows 上运行:

Windows tasklist command:

Windows 任务列表命令:

The DOS command tasklistshows some output on what processes are running:

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>

The second column is the PID

第二列是PID

You can use tasklistto get info on a specific PID:

您可以使用tasklist获取有关特定 PID 的信息:

tasklist /FI "PID eq 1300"

prints:

印刷:

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

C:\Documents and Settings\eric>

A response means the PID is running.

响应意味着 PID 正在运行。

If you query a PID that does not exist, you get this:

如果查询不存在的 PID,则会得到以下信息:

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

A Java function could do the above automatically

Java 函数可以自动执行上述操作

This function will only work on Windows systems that have tasklistavailable.

此功能仅适用于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.");
        }
    }
}

The Java code above prints a list of all running processes then prints:

上面的 Java 代码打印所有正在运行的进程的列表,然后打印:

is PID 1300 running? true

回答by aprodan

Code:

代码:

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

回答by Gal Levy

  1. import jna from Maven to your project
  2. after maven was update you can use:
  1. 将 jna 从 Maven 导入到您的项目中
  2. Maven 更新后,您可以使用:

int myPid = Kernel32.INSTANCE.GetCurrentProcessId();

int myPid = Kernel32.INSTANCE.GetCurrentProcessId();