std::system只能执行命令并返回退出码,无法捕获stdout/stderr;推荐用popen(POSIX)或_popen(Windows)读取stdout,但需注意单向通信、必须pclose、缓冲区安全及shell注入风险。
std::system 只能执行命令,拿不到输出很多人一上来就写 std::system("ls -l"),发现程序能运行命令,但 stdout 完全看不到——std::system 本质是 fork + exec + wait,输出直接打到终端,不经过你的程序。想捕获结果,必须换路子。
popen(POSIX)读取 stdoutpopen 是最轻量、最常用的方式,适用于 Linux/macOS;Windows 上可用 _popen(需 <cstdio>,行为基本一致)。它返回 FILE*,可像读文件一样读命令输出。
注意点:
"r" 模式读 stdout,开 "w" 模式写 stdin(极少用)pclose(),否则子进程变成僵尸,且资源泄漏fgets 或 fread)$、`),否则有注入风险;若需拼接变量,务必做白名单校验或用 exec 系列替代简单示例:
立即学习“C++免费学习笔记(深入)”;
#include <cstdio>#include <string>#include <vector><p>std::string exec(const char<em> cmd) {FILE</em> pipe = popen(cmd, "r");if (!pipe) return "";char buffer[128];std::string result;while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {result += buffer;}pclose(pipe);return result;}</p><p>// 用法:auto out = exec("ps aux | grep myapp");
fork + pipe + exec
当需要精确控制(比如同时捕获 stdout/stderr、设置超时、避免 shell 解析)时,popen 不够用。这时得手动建 pipe、fork 子进程、重定向 fd、再 exec。Windows 对应是 CreateProcess + ReadFile,逻辑更啰嗦。
关键细节:
close 写端 fd,否则 read 不会 EOFexec 前 dup2 把 pipe 写端复制成 STDOUT_FILENO(和 STDERR_FILENO,如果也要捕获)waitpid 获取退出码,否则子进程残留常见翻车点:
std::string::c_str() 传给 popen,但字符串临时对象生命期短于 popen 调用——结果未定义行为;应先存为局部 std::string 变量再取 c_str()
popen 支持 Windows 的 cmd 内置命令(如 dir),实际需要写 "cmd /c dir";Linux 下 ls 可直接用,因为 /bin/sh 默认存在getline 配合 std::istream 包装popen 返回 nullptr 表示 fork/exec 失败(如命令不存在),不是输出为空真正难的从来不是“怎么调用”,而是“怎么安全地拼命令、怎么可靠地收数据、怎么不卡死、怎么清理干净”。尤其在线程里用,fd 和信号处理稍不注意就崩。