You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows 11中用C++及Windows.h内置库获取所有运行程序与进程

C++标准库本身没有提供枚举系统进程的通用接口,得依赖目标平台的原生API来实现,下面分Windows和Linux两种常见场景给你具体方案:

Windows平台实现

Windows下可以用ToolHelp32系列API来枚举进程,这是微软提供的专门用于系统快照的工具集:

  • 核心函数:CreateToolhelp32Snapshot(创建进程快照)、Process32First(获取第一个进程信息)、Process32Next(遍历后续进程)
  • 需要包含头文件windows.h和tlhelp32.h

示例代码:

#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <string>

int main() {
    // 创建包含所有进程的快照
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        std::cerr << "创建快照失败,错误码: " << GetLastError() << std::endl;
        return 1;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32); // 必须初始化结构体大小

    // 获取第一个进程的信息
    if (!Process32First(hSnapshot, &pe32)) {
        std::cerr << "读取第一个进程失败,错误码: " << GetLastError() << std::endl;
        CloseHandle(hSnapshot);
        return 1;
    }

    // 遍历所有进程
    do {
        std::cout << "PID: " << pe32.th32ProcessID 
                  << " | 进程名: " << pe32.szExeFile << std::endl;
    } while (Process32Next(hSnapshot, &pe32));

    CloseHandle(hSnapshot);
    return 0;
}

编译提示:用VS直接编译即可,或者用MinGW编译时需要链接kernel32库:g++ process.cpp -o process -lkernel32

Linux平台实现

Linux的进程信息都存放在/proc虚拟文件系统中,每个以数字命名的文件夹对应一个进程的PID,通过读取这些文件夹下的文件就能获取进程信息:

  • 用dirent.h提供的函数遍历/proc目录,筛选出数字命名的文件夹(即PID)
  • 读取/proc/[PID]/comm文件可以获取进程名,读取/proc/[PID]/status能拿到更详细的信息

示例代码:

#include <iostream>
#include <dirent.h>
#include <string>
#include <fstream>
#include <cctype>

// 判断字符串是否为数字(用于筛选PID文件夹)
bool is_number(const std::string& s) {
    for (char c : s) {
        if (!isdigit(c)) return false;
    }
    return !s.empty();
}

int main() {
    DIR* proc_dir = opendir("/proc");
    if (!proc_dir) {
        std::cerr << "无法打开/proc目录" << std::endl;
        return 1;
    }

    struct dirent* entry;
    while ((entry = readdir(proc_dir)) != nullptr) {
        std::string pid_str = entry->d_name;
        if (is_number(pid_str)) {
            std::string comm_path = "/proc/" + pid_str + "/comm";
            std::ifstream comm_file(comm_path);
            std::string proc_name;
            
            if (comm_file.is_open()) {
                std::getline(comm_file, proc_name);
                std::cout << "PID: " << pid_str << " | 进程名: " << proc_name << std::endl;
                comm_file.close();
            } else {
                // 无权限读取的进程直接跳过
                continue;
            }
        }
    }

    closedir(proc_dir);
    return 0;
}

编译提示:直接用g++编译即可:g++ process.cpp -o process,普通用户可能无法读取部分系统进程,需要用sudo运行才能看到完整列表。

额外提示

如果需要跨平台实现,可以考虑使用第三方库(比如Qt的QProcess类、Boost.Process)来封装不同平台的API;如果坚持原生C++,可以用#ifdef做平台分支判断,把不同平台的代码分开实现。

内容的提问来源于stack exchange,提问作者snapshot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:54:55