Код:
Код: Выделить всё
#include
#include
#include
#include
#include
std::string exec_command(const char* cmd) {
std::array buffer;
std::string result;
std::unique_ptr pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
int main() {
// Simple reproducible example
const char* test_cmd = "ps aux | grep bash";
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79240200/c-popen-fails-to-capture-output-from-bash-pipeline-commands-on-ubuntu-22-04[/url]