I need to run a Linux CLI command and get its stdout output from C.
I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.
Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.
There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status.
Here is what I use:
Is this it?
Use
popen()
andpclose()
.popen()
does not actually wait, of course, but reads on the pipe will block until there is data available.pclose()
waits, but calling it prematurely could cut off some output from the forked process. You'll want to determine from the stream when the child is done...Possibly already discussed at How can I run an external program from C and parse its output?
GLib has a nice function for this --
g_spawn_sync()
: http://library.gnome.org/devel/glib/stable/glib-Spawning-Processes.html#g-spawn-syncFor example, to run a command and get its exit status and output: