Interacting with a Shell using C
The UNIX styled popen() function is what you want to use.See the man page for specifics.
It runs your command in a subprocess and gives you a pipe to interact with it. It returns a FILE handle like fopen() does, but you close it with pclose() rather than fclose(). Otherwise you can interact with the pipe the same way as for a file stream. Very easy to use and useful.
Here's a link to a use case example
Also check out this example illustrating a way to do what you are trying to do:
#include <stdio.h>int main(void) { FILE *in; extern FILE *popen(); char buf[512]; if (!(in = popen("ls -sail", "r"))) exit(1); while (fgets(buf, sizeof(buf), in) != NULL) printf("%s", buf); pclose(in);}