C++/Linux run an external command and get output

Red Squirrel

No Lifer
May 24, 2003
71,312
14,084
126
www.anyf.ca
What is a way in C++ to run a Linux shell command (basically equivalent to typing it in the standard shell environment) and get the output?

I know with system() I can run a command, but there is no way to get the output unless I specificly pipe it to a file then read that file. I'm looking for a way to do it on the fly.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
You want standard output (stdout). In Windows you can use an option to the CreateProcess call to redirect standard output. I'm not sure what the right method is in Linux.
 

bobross419

Golden Member
Oct 25, 2007
1,981
1
0
I'm assuming that C++ is similar to Perl in this regard, but those system calls are much more expensive than the same actions performed in code. If its something that will be run quite frequently and doesn't require you to rewrite an entire package it might be beneficial to source dive the other package and see if you can get it working in code.
 

Red Squirrel

No Lifer
May 24, 2003
71,312
14,084
126
www.anyf.ca
Yeah normally I would not do it that way, but this is for a monitoring program where data comes from the output of various commands such as cat, sed etc... so the full command is put as part of the config file for each monitor. Using this method I can monitor literally anything by just putting the right command, or script. In this case ms differences don't really matter.

There's also the security issue where if someone maliciously has access to the config files puts something like rm -rf / then the app will execute it, but this is meant to run on a stand alone system that nobody should have access to.