Qt中获取Shell返回值

背景:Qt中需要通过应用层执行shell相关命令,有的时候还需要得到执行完毕后的返回值。

.h

#ifndef EXEC_SHELL_H
#define EXEC_SHELL_H

#include<iostream>
#include<memory>
#include<string>
#include<array>
#include<QDebug>

using namespace::std;
string exec_shell(const char* cmd);

#endif // EXEC_SHELL_H

.cpp

#include"exec_shell.h"

string exec_shell(const char* cmd)
{
    array<char, 1024>buffer;
    string result;
    unique_ptr<FILE, decltype (&pclose)> pipe(popen(cmd,"r"), pclose);
    if(!pipe){
        throw runtime_error("Popen() failed!!!");
    }
    while(fgets(buffer.data(),buffer.size(),pipe.get()) != nullptr){
        result += buffer.data();
    }
    return result;
}
发布了146 篇原创文章 · 获赞 160 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/baidu_33879812/article/details/104541325