linux c++ 调用调用shell命令,保存执行结果命令,保存执行结果 示例示例
下面的代码用于在c++函数里面调用shell,并且执行命令,取回命令执行结果。
#include
#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"; // 要执行的命令
if (system(nullptr) == 0) // 查看shell是否可用
{
std::cout << "shell not available" << std::endl;
return 1;
}
auto cmdOut = popen(cmd_.c_str(), "r"); // 执行命令
if (cmdOut == nullptr)
{
std::cout << "popen error" <= MAX_RESPONSE_SIZE)
{
result_.append(charBuff, MAX_RESPONSE_SIZE - bytesRead);
break;
}
else
{
result_.append(charBuff);
}
bytesRead += strlen(charBuff);
}
closeResult = pclose(cmdOut); // 关闭
std::cout << "bytesRead=" << bytesRead << std::endl;
std::cout << "closeResult=" << closeResult << std::endl;
std::cout << "WEXITSTATUS(closeResult)=" << WEXITSTATUS(closeResult) << std::endl;
std::cout << "result=" << result_ << std::endl;
return 0;
}
结果如下
[root@test shell]# ./main
bytesRead=246
closeResult=0
WEXITSTATUS(closeResult)=0
result=total 20
drwxr-xr-x 3 root root 49 Dec 5 08:00 .
drwxr-xr-x 5 root root 92 Dec 5 07:40 ..
-rwxr-xr-x 1 root root 14416 Dec 5 08:00 main
-rw-r--r-- 1 root root 1205 Dec 5 08:00 main.cpp
作者:纠结的绳子
评论0