Код: Выделить всё
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv [])
{
FILE* pipe;
char buf [BUFSIZ];
if (argc != 2)
{
fprintf (stderr, "Usage: %s COMMAND\n", argv [0]);
exit (1);
}
printf ("Trying to execute command `%s'\n", argv [1]);
if ((pipe = popen (argv [1], "r")) == NULL)
{
perror (argv [1]);
exit (1);
}
while (fgets (buf, BUFSIZ, pipe) != NULL)
printf ("Got line: %s", buf);
if (ferror (pipe))
perror (argv [1]);
pclose (pipe);
exit (0);
}
Открываем пайп и читаем из него как из файла.
Код
[nameless@desktop c]$ ./sample 'ls -l'
Trying to execute command `ls -l'
Got line: итого 32
Got line: -rw-rw-r--. 1 nameless nameless 527 марта 6 20:59 main.c
Got line: -rw-rw-r--. 1 nameless nameless 854 марта 6 18:27 main.c~
Got line: -rw-rw-r--. 1 nameless nameless 6768 марта 6 20:59 main.o
Got line: -rw-rw-r--. 1 nameless nameless 302 марта 2 13:05 Makefile
Got line: -rwxrwxr-x. 1 nameless nameless 10295 марта 6 20:59 sample
[nameless@desktop c]$