如何在Mac OSX中用C++获取指定进程的PID并保存为变量
嘿,我来给你分享几个在macOS上用C++获取指定程序PID并存为变量的实用方案,都是实际试过可行的:
方法1:调用系统命令
pgrep解析输出 macOS自带pgrep命令,可以直接根据程序名筛选PID,我们可以在C++里通过popen执行这个命令,然后读取输出转换成PID变量。这种方法简单直观,适合快速实现。
#include <iostream> #include <cstdio> #include <string> #include <cstdlib> int main() { const std::string targetProgram = "Safari"; // 替换成你要查找的程序名 std::string cmd = "pgrep -x " + targetProgram; // -x 参数确保精确匹配程序名 // 执行命令并获取输出管道 FILE* pipe = popen(cmd.c_str(), "r"); if (!pipe) { std::cerr << "执行命令失败!" << std::endl; return EXIT_FAILURE; } char buffer[128]; std::string pidOutput; // 读取命令输出 while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { pidOutput += buffer; } pclose(pipe); if (!pidOutput.empty()) { // 将输出的字符串转为整数类型的PID pid_t targetPid = std::stoi(pidOutput); std::cout << "找到的PID:" << targetPid << std::endl; // 这里就可以把targetPid作为变量用于后续逻辑了 } else { std::cerr << "未找到匹配的进程!" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
注意点:
- 如果目标程序名包含空格或特殊字符,需要给程序名加上引号,比如:
std::string cmd = "pgrep -x \"" + targetProgram + "\""; - 如果程序有多个运行实例,
pgrep会输出多个PID(每行一个),上面的代码只取第一个,要是需要收集所有PID,可以循环读取每一行并存入数组。
方法2:使用macOS原生API(更可靠)
如果不想依赖外部命令,推荐用macOS提供的原生进程查询API,比如proc_listallpids和proc_pidpath,这些API属于系统库,不需要调用外部进程,稳定性和性能更好。
#include <iostream> #include <vector> #include <string> #include <cstdint> #include <libproc.h> #include <cstdlib> int main() { const std::string targetName = "Safari"; pid_t foundPid = -1; // 先获取系统中所有进程的PID数量 int pidCount = proc_listallpids(nullptr, 0); if (pidCount <= 0) { std::cerr << "获取进程数量失败!" << std::endl; return EXIT_FAILURE; } // 分配空间存储所有PID std::vector<pid_t> allPids(pidCount); pidCount = proc_listallpids(allPids.data(), allPids.size() * sizeof(pid_t)); if (pidCount <= 0) { std::cerr << "读取进程列表失败!" << std::endl; return EXIT_FAILURE; } // 遍历每个PID,匹配程序名 for (pid_t pid : allPids) { char procPath[PROC_PIDPATHINFO_MAXSIZE]; // 获取进程的可执行文件路径 if (proc_pidpath(pid, procPath, sizeof(procPath)) > 0) { std::string pathStr(procPath); // 从路径中提取程序名(比如从/Applications/Safari.app/Contents/MacOS/Safari提取Safari) size_t lastSlash = pathStr.find_last_of('/'); if (lastSlash != std::string::npos) { std::string procName = pathStr.substr(lastSlash + 1); if (procName == targetName) { foundPid = pid; break; // 找到第一个匹配的就退出,要找所有实例可以去掉break } } } } if (foundPid != -1) { std::cout << "找到的PID:" << foundPid << std::endl; // 这里可以使用foundPid变量进行后续操作 } else { std::cerr << "未找到匹配的进程!" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
编译注意:
编译这个代码时需要链接libproc库,比如用g++的话执行:
g++ -o get_pid get_pid.cpp -lproc
总结:
- 方法1适合快速实现,代码量小,但依赖系统命令
- 方法2是原生方案,更可靠,适合对稳定性要求高的场景
内容的提问来源于stack exchange,提问作者N T
相关产品推荐
相关产品推荐

