popen()将执行的命令输出写入cout [英] popen() writes output of command executed to cout
问题描述
我正在编写一个需要打开另一个进程并获取其输出的应用程序.在我读过的所有地方都在线上,我必须使用popen
并从文件中读取.
I am writing an application that needs to open another process and get it's output. Online everywhere I read I have to use popen
and read from the file.
但是我看不懂它.命令的输出将输出到调用应用程序的控制台窗口中.下面是我正在使用的代码.我添加了一些印刷品进行调试.
But I can't read from it. The output of the command gets output into the console window of the calling application. Below is the code I am using. I added some prints to debug.
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <array>
int main()
{
// some command that fails to execute properly.
std::string command("ls afskfksakfafkas");
std::array<char, 128> buffer;
std::string result;
std::cout << "Opening reading pipe" << std::endl;
FILE* pipe = popen(command.c_str(), "r");
if (!pipe)
{
std::cerr << "Couldn't start command." << std::endl;
return 0;
}
while (fgets(buffer.data(), 128, pipe) != NULL) {
std::cout << "Reading..." << std::endl;
result += buffer.data();
}
auto returnCode = pclose(pipe);
std::cout << result << std::endl;
std::cout << returnCode << std::endl;
return 0;
}
从不真正将读数打印到我的cout
上,结果是一个空字符串.我在终端中清楚地看到了命令的输出.如果命令正常退出,则行为符合预期.但是我只捕获错误情况下的输出.
Reading is never actually printed to the my cout
and result is an empty string. I clearly see the output of the command in my terminal. If the command exits gracefully the behaviour is as expected. But I only capture the output for error cases.
推荐答案
Popen不能捕获仅stderr标准输出.将stderr重定向到stdout可以解决此问题.
Popen doesn't capture stderr only stdout. Redirecting stderr to stdout fixes the issue.
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <array>
int main()
{
std::string command("ls afskfksakfafkas 2>&1");
std::array<char, 128> buffer;
std::string result;
std::cout << "Opening reading pipe" << std::endl;
FILE* pipe = popen(command.c_str(), "r");
if (!pipe)
{
std::cerr << "Couldn't start command." << std::endl;
return 0;
}
while (fgets(buffer.data(), 128, pipe) != NULL) {
std::cout << "Reading..." << std::endl;
result += buffer.data();
}
auto returnCode = pclose(pipe);
std::cout << result << std::endl;
std::cout << returnCode << std::endl;
return 0;
}
这篇关于popen()将执行的命令输出写入cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!