从进程名称获取进程的ID [英] Getting The ID of a process from Process name

查看:505
本文介绍了从进程名称获取进程的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一个进程的ID,我只有它的名字,我知道只有一个实例将一次运行,所以不会有一个问题与多个进程与同一个名称的一个'm正在寻找。

I need to find the ID of a process and I only have its name, I know that only 1 instance will be running at one time so there's not going to be a problem with multiple processes with the same name as the one i'm looking for.

如果有人可以解释如何从一个进程的名称获取进程的ID,我将非常感谢。 brilliant。

I would greatly appreciate it if somebody could explain how I could go about getting the ID of a process from just its name - and code examples would be brilliant.

推荐答案

从您的其他问题( RegSetValueEx 使它有点明显),我会假设你在Windows上。对于纯Windows API解决方案,您可以使用Toolhelp32 API来查看正在运行的进程的快照,并将其名称与您要查找的名称进行比较。您只有一个名称的注意事项,但未来可能会有利于拥有该名称的所有PID,因此我将这样做:

Judging from your other questions (RegSetValueEx in the title makes it somewhat obvious), I'll presume you're on Windows. For a pure Windows API solution, you can use the Toolhelp32 API to go through a snapshot of the running processes and compare their names to the name you're looking for. You have the note about only one name, but it might be beneficial in the future, or to someone else, to have all PIDs for that name, so I'll do that:

std::vector<DWORD> pids;

HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //all processes

PROCESSENTRY32W entry; //current process
entry.dwSize = sizeof entry;

if (!Process32FirstW(snap, &entry)) { //start with the first in snapshot
    return 0;
}

do {
    if (std::wstring(entry.szExeFile) == wantedProcessName) {
        pids.emplace_back(entry.th32ProcessID); //name matches; add to list
    }
} while (Process32NextW(snap, &entry)); //keep going until end of snapshot

这篇关于从进程名称获取进程的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆