从流程名称获取流程ID

时间:2012-10-21 12:18:17

标签: java windows scala jna pid

我正在使用Scala,但我找不到能从Processname中获取PrcoessID的东西。无论是Java,Scala还是Winapi。

目前我正在使用FindWindowAGetWindowThreadProcessId,但我更喜欢能给我一个阵列的东西

val process: Array[Int] = GetProcessIdFromExeName("Notepad")

因此,如果我有10个记事本实例,我可以使用process(0-9)

访问它们

我知道.NET中存在这样的东西,但是在WINAPI或Java / Scala中是否存在类似内容?

2 个答案:

答案 0 :(得分:1)

最简单的方法是运行tasklist并解析输出。请参阅此资源以供参考:

https://stackoverflow.com/questions/53489/how-do-you-list-all-processes-on-the-command-line-in-windows

您也可以使用WMI。编写执行WMI查询并打印输出的JScript或VBScript非常简单,因此您可以从java或Scala进程运行它并解析输出。 WMI提供的选项多于tasklist

如果您选择WMI,您也可以使用现有的java-to-com库之一来调用它,例如JaWin,Jintegra,JInterop。

答案 1 :(得分:0)

老问题;但是,我刚才写了这个课:

 public class TaskList {
    public static final String PROCESS_NAME = "tasklist";
    private static final String LINE_FORMAT = "%-25s %14s %-16s %14s %15s\n";

    public static Process getTaskListProcess() throws IOException {
        return Runtime.getRuntime().exec(PROCESS_NAME);
    }

    List<TaskListEntry> taskListEntries;
    boolean hasRun;

    public TaskList() {
        taskListEntries = new ArrayList<>();
    }

    public void run() {
        if (hasRun) {
            // intentions of running this twice is not clear so throw exception
            String err = "TaskList can only be run once";
            throw new IllegalStateException(err);
        }

        try {
            Process proc = getProcess();
            List<String> lines = Processes.getAllLines(proc);

            String[] seperators = lines.get(2).split(" ");
            if (seperators.length < 5) {
                throw new IllegalStateException("Incorrect number of seperators parsed");
            }

            // Remove header and separators
            lines = lines.subList(4, lines.size() - 1);

            for (String line : lines) {
                taskListEntries.add(new TaskListEntry(seperators, line));
            }
        } catch (IOException e) {
            String err = "Error resolving process";
            throw new IllegalStateException(err, e);
        }
    }

    Process getProcess() throws IOException {
        return getTaskListProcess();
    }

    public List<TaskListEntry> getTaskListEntries() {
        return Collections.unmodifiableList(taskListEntries);
    }


    @Override
    public String toString() {
        String sep = "============================";
        String headers = String.format(LINE_FORMAT, "Image Name", "PID", "Session Name", "Session#", "Mem Usage");
        StringBuilder builder = new StringBuilder(headers);
        builder.append(sep).append(" ")
            .append(sep.substring(17)).append(" ")
            .append(sep.substring(9)).append(" ")
            .append(sep.substring(17)).append(" ")
            .append(sep.substring(13)).append('\n');

        for(TaskListEntry entry : getTaskListEntries()) {
            builder.append(entry.toString());
        }
        return builder.toString();
    }

    public class TaskListEntry {
        private TaskListEntry(String[] seperators, String line) {
            try {
                int start = 0;
                int end = start + seperators[0].length() + 1;
                this.image = line.substring(start, end).trim();

                start = end;
                end = start + seperators[1].length() + 1;
                this.pid = Integer.parseInt(line.substring(start, end).trim());

                start = end;
                end = start + seperators[2].length() + 1;
                this.sessionName = line.substring(start, end).trim();

                start = end;
                end = start + seperators[3].length() + 1;
                this.sessionNum = Integer.parseInt(line.substring(start, end).trim());

                start = end;
                end = start + seperators[4].length();
                this.memUsage = line.substring(start, end).trim();
            } catch (NullPointerException e) {
                throw e;
            } catch (RuntimeException e) {
                String format = "Unable to parse line {%s} with seperator {%s}";
                String msg = String.format(format, line, Arrays.toString(seperators));
                throw new IllegalArgumentException(msg, e);
            }

        }

        String image;
        int pid;
        String sessionName;
        int sessionNum;
        String memUsage;

        @Override
        public String toString() {
            return String.format(LINE_FORMAT, image, pid, sessionName, sessionNum, memUsage);
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public int getPid() {
            return pid;
        }

        public void setPid(int pid) {
            this.pid = pid;
        }

        public String getSessionName() {
            return sessionName;
        }

        public void setSessionName(String sessionName) {
            this.sessionName = sessionName;
        }

        public int getSessionNum() {
            return sessionNum;
        }

        public void setSessionNum(int sessionNum) {
            this.sessionNum = sessionNum;
        }

        public String getMemUsage() {
            return memUsage;
        }

        public void setMemUsage(String memUsage) {
            this.memUsage = memUsage;
        }
    }


 public static void main(String [] args){
        TaskList tasks = new TaskList();
        tasks.run();
        tasks.getTaskListEntries();
        Optional<TaskListEntry> entry  = tasks.getTaskListEntries()
                .stream()
                .filter(p -> p.getImage().equals("notepad++.exe"))
                .findFirst();

        if(entry.isPresent()) {
            logger.info(entry.get());
        }
    }
}

这是引用的Processes类

public class Processes {

    public static BufferedReader getProcessReader(Process p) {
        InputStream in = p.getInputStream();
        InputStreamReader reader = new InputStreamReader(in);
        return new BufferedReader(reader);
    }

    public static List<String> getAllLines(Process p) {
        try (BufferedReader reader = getProcessReader(p)) {
            List<String> lines = new ArrayList<>();
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
            return lines;
        } catch (IOException e) {
            String msg = "Reader is not in a readable state";
            throw new IllegalStateException(msg, e);
        }
    }

    private Processes() {
        // This is a utility method
    }
}