我试图在 Linux 上运行一个命令并检索输出,我发现了一些代码,但是当我运行它时,我得到了第一行,然后线程被阻塞了。这是代码:
std::string exec_cmd(char const* cmd)
{
std::string result, file;
FILE* pipe {popen(cmd, "r")};
char buffer[256];
while(fgets(buffer, sizeof(buffer), pipe) != nullptr)
{
file = buffer;
result += file.substr(0, file.size() - 1);
}
pclose(pipe);
return result;
}
例如,如果我正在运行命令 uname -a
,我会退出,但 fgets
等待数据,执行会卡在那里。
我正在使用 JNI。
有人能帮帮我吗?
最佳答案
代码应该可以工作,但我会使用我的 pstream.h
标题改为:
std::string exec_cmd(char const* cmd)
{
redi::ipstream p(cmd);
std::ostringstream result;
result << p.rdbuf();
return result.str();
}
或者,如果实际需要原始代码的换行剥离行为:
std::string exec_cmd(char const* cmd)
{
redi::ipstream p(cmd);
std::string result, line;
while (std::getline(p, line))
result += line;
return result;
}
这只会去除换行符,不会丢失超过 256 字节的行中的数据。
关于c++ - 尝试使用 C++ 在 Linux 上执行命令时被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29209438/