C++程序要跟Linux命令行打交道,这活儿主要有两种搞法:一种是直接用系统调用,另一种是走管道。

1. 使用系统调用(system()函数)
最直接的方式,就是调用system()函数。这个函数接受一个字符串参数,里面放的就是你想执行的Linux命令。比如下面这个例子:
#include int main() {system("ls -l");return 0;} 程序跑起来之后,会执行ls -l,然后屏幕上一闪而过目录列表。不过有个问题得注意——system()是阻塞的,也就是说,它不等到命令执行完,程序是不会继续往下走的。
2. 使用管道(popen()函数)
如果觉得system()太死板,不够灵活,那popen()就是更高级的选择。它允许你在C++程序里创建一个管道,跟外部进程双向通信,既能接收命令的输出,也能向命令发送输入。来看一个封装好的例子:
#include #include #include #include std::string exec(const char* cmd) {std::array buffer;std::string result;std::shared_ptr pipe(popen(cmd, "r"), pclose);if (!pipe) throw std::runtime_error("popen() failed!");while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {result += buffer.data();}return result;}int main() {std::string output = exec("ls -l");std::cout << output;return 0;} 这个例子通过popen()执行ls -l,然后把输出逐行读出来,存到字符串里,最后打印到控制台。相比system(),管道方式明显更灵活——你可以处理标准输出和错误流,甚至可以主动向命令发送数据。
总结一下:system()简单粗暴,适合那种“只管执行、不管结果”的场景;而popen()则更像一个可控的交互通道,在实战中更推荐优先考虑。