我正在寻找一种方法,在C++程序内运行命令并获取其输出。我已经尝试使用system()
函数,但那只会执行一个命令。以下是我想要的示例:
std::string result = system("./some_command");
我需要运行任意命令并获取其输出。我查看了boost.org,但是我没有找到能够满足我的需求的内容。
运行脚本后,您可以使用管道获取输出。当我们想要子进程的输出时,我们使用管道。
int my_func() {
char ch;
FILE *fpipe;
FILE *copy_fp;
FILE *tmp;
char *command = (char *)"/usr/bin/my_script my_arg";
copy_fp = fopen("/tmp/output_file_path", "w");
fpipe = (FILE *)popen(command, "r");
if (fpipe) {
while ((ch = fgetc(fpipe)) != EOF) {
fputc(ch, copy_fp);
}
}
else {
if (copy_fp) {
fprintf(copy_fp, "Sorry there was an error opening the file");
}
}
pclose(fpipe);
fclose(copy_fp);
return 0;
}
int my_func(){
char *command = (char *)"/usr/bin/my_script my_arg > /tmp/my_putput_file";
system(command);
printf("everything saved in my_output_file");
return 0;
}
#include <istream>
#include <streambuf>
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
class execbuf : public std::streambuf {
protected:
std::string output;
int_type underflow(int_type character) {
if (gptr() < egptr()) return traits_type::to_int_type(*gptr());
return traits_type::eof();
}
public:
execbuf(const char* command) {
std::array<char, 128> buffer;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
this->output += buffer.data();
}
setg((char*)this->output.data(), (char*)this->output.data(), (char*)(this->output.data() + this->output.size()));
}
};
class exec : public std::istream {
protected:
execbuf buffer;
public:
exec(char* command) : std::istream(nullptr), buffer(command, fd) {
this->rdbuf(&buffer);
}
};
这段代码捕捉了通过 stdout
输出的所有内容。如果你只想捕捉 stderr
,则需要像这样传递命令:
sh -c '<your-command>' 2>&1 > /dev/null
stdout
和 stderr
,则命令应该如下所示:sh -c '<your-command>' 2>&1
#include <array>
并移除 , fd
以使其编译。 - truf
https://dev59.com/6lQK5IYBdhLWcg3wQdvI
。该问题的回答扩展了下面这个很好的答案,提供了获取return code
、stderr
和本回答已经解释的stdout
的方法。请注意,不要更改原始意思,并尽可能使翻译通俗易懂。 - code_fodder