如何在 C++ 中使用 POSIX 执行命令并获取命令的输出?
你可以使用 popen 和 pclose 函数在进程中进行管道通信。popen() 函数通过创建管道、fork 和调用 shell 来打开一个进程。我们可以使用一个缓冲区读取 stdout 的内容,并将其一直附加到一个结果字符串中,并在进程退出时返回这个字符串。
示例
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;
string exec(string command) {
char buffer[128];
string result = "";
// Open pipe to file
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) {
return "popen failed!";
}
// read till end of process:
while (!feof(pipe)) {
// use buffer to read and add to result
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main() {
string ls = exec("ls");
cout << ls;
}输出
这将给出输出 -
a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP