Avatar ·

How to execute a command and get its output in C++ (POSIX)?

Hello, colleagues! I just started learning C++ on Linux and ran into a task: I need to execute an external command (e.g., `ls -la` or `ping google.com`) and get its output directly in the program. I tried `system()` — it works, but it only returns the exit code, and the output itself is printed to the console. I need to capture this output into a string to process it later.\n\nFor example, I'm writing a utility that checks which processes are running. I want to execute `ps aux` and analyze the result. But how can I do this in C++ in POSIX style? I've heard about `popen()`, but I'm not sure it's the best way. There's also `fork()`, `exec()`, `pipe()` — this looks complicated for a beginner. Maybe there's some simple and reliable method?\n\nHere's my current code that doesn't work as expected:\n\n```cpp\n#include \n#inc