本示例展示如何在Linux环境下使用C++编程语言调用Shell命令,并将命令执行的结果捕获和保存下来。通过实例代码帮助开发者理解和实现这一功能,适用于需要进行系统交互的应用场景。
下面的代码用于在C++函数里面调用shell,并且执行命令,取回命令执行结果。
```cpp
#include
#include
#include
int main() {
const int SIZE = 64;
const int MAX_RESPONSE_SIZE = 65535;
char charBuff[SIZE];
int bytesRead = 0;
int closeResult;
std::string result_;
std::string cmd_ = ls -al; // 要执行的命令
FILE* pipe = popen(cmd_.c_str(), r);
if (!pipe) {
throw std::runtime_error(Failed to open pipe for command execution.);
}
while (fgets(charBuff, SIZE, pipe)) {
bytesRead += strlen(charBuff);
result_ += charBuff;
}
closeResult = pclose(pipe);
if (closeResult == -1) {
throw std::runtime_error(Error closing the pipe after executing command);
}
// 执行结果存储在result_中
}
```