I'm building a simple process monitoring tool that needs to execute and capture bash command outputs through C++. The weird part: same commands work perfectly in terminal but fail through C++.
Code:
#include <cstdio>#include <iostream>#include <memory>#include <string>#include <array>std::string exec_command(const char* cmd) { std::array<char, 128> buffer; std::string result; std::unique_ptr<FILE, decltype(&pclose)> 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 << "Running: " << test_cmd << std::endl; try { std::string output = exec_command(test_cmd); std::cout << "Output: " << output << std::endl; } catch(const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0;}Environment (Reproducible on):
- OS: Ubuntu 22.04 LTS
- Compiler: GCC 11.3.0 (
g++ --versionoutput below) - Shell: Bash 5.1.16
g++ (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0Terminal vs Program Output:
Terminal output (works):
$ ps aux | grep bashroot 1234 0.0 0.1 9720 5236 pts/0 Ss 10:00 0:00 -bashuser 5678 0.0 0.1 9720 5236 pts/1 Ss+ 10:01 0:00 bashProgram output (fails):
$ ./a.outRunning: ps aux | grep bashOutput: Debug Information:
strace output snippet:
$ strace ./a.out...pipe2([3, 4], O_CLOEXEC) = 0clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f9b2c7fe9d0) = 12345...What I've tried (in order):
- Basic troubleshooting:
- Running with sudo
- Using system() instead of popen()
- Different buffer sizes
- Advanced debugging:
- strace monitoring
- valgrind memory checks
- Different shell commands without pipes
Expected behavior:
Program should capture and display the same output as running the command directly in terminal.
Question:
What's causing this discrepancy between terminal and C++ execution, and how can I properly capture piped command output in Ubuntu 22.04?
Notes:
- No error messages or return codes
- Works fine on Debian 11 with same GCC version
- All files/processes have correct permissions
- Issue happens with any piped command, not just this example...