コマンドを実行し、標準出力、標準エラー出力の両方をペアにして返す関数を作りたいです。
それぞれ別々に取得するには以下のようにしてできましたが、1度だけのコマンドの実行で実現するにはどうすれば良いでしょうか。
ファイルに書き出すという方法も思い浮かびましたが、できたらパイプやCの関数を上手く使って実現したいです。
よろしくお願いします。
#include <bits/stdc++.h>
#include <unistd.h>
using namespace std;
string execCommand(string com){
com += " 2> /dev/null";
cout << com << endl;
FILE *p = popen(com.c_str(), "r");
char c;
string out;
while((c = getc(p)) != EOF) out += c;
pclose(p);
return out;
}
string execCommand2(string com){
com += " 2>&1 >/dev/null";
cout << com << endl;
FILE *p = popen(com.c_str(), "r");
char c;
string out;
while((c = getc(p)) != EOF) out += c;
pclose(p);
return out;
}
int main(){
{
cout << "----- [stdout] -----" << endl;
string out = execCommand("wget \"http://www.google.co.jp\" -O -");
if(out.size() > 80) out.resize(80);
cout << out << endl;
}
sleep(1);
{
cout << "----- [stderr] -----" << endl;
string out = execCommand2("wget \"http://www.google.co.jp\" -O -");
if(out.size() > 80) out.resize(80);
cout << out << endl;
}
}