我正在运行 MacOS,想要通过我的应用程序执行 "ps aux" 命令并获取其输出。我已经编写了一个使用 popen 函数执行命令的方法:
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!2");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
我有一个循环,不断运行exec("ps aux")函数。问题在于popen的管道没有关闭,我使用终端的"lsof"命令进行了检查。大约20秒后,应用程序会打开300个以上的文件描述符,这会阻止应用程序从循环中打开更多的管道(运行"ps aux"命令)。
我发现,exec函数对其他命令(管道正确关闭)也能正常工作,例如"netstat",因此必须是"ps aux"命令中的某些内容导致了管道无法关闭。
我已经搜索了很多关于这个问题的解决方案,但没有找到任何答案。请问有人可以指点我正确的方向吗?
谢谢!
struct PipeCloser { void operator()(FILE* f) { pclose(f); } }; using PipeUniquePtr = std::unique_ptr<FILE, PipeCloser>;
。 - Daniel Schepler