Initial import of popen_ls.c
[eleutheria.git] / ipc / popen_ls.c
blob573aeadba30792f0bcab95724ba0a51e50336c1d
1 #include <err.h> /* for errx() */
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <sys/wait.h> /* for waitpid() macros */
6 #define MAX_STR 100
8 int main(void)
10 char str[MAX_STR];
11 int ret;
12 FILE *fp;
14 /* Initiate pipe stream to ``ls'' */
15 fp = popen("ls", "r");
16 if (fp == NULL)
17 errx(EXIT_FAILURE, "popen()");
19 /* Read from stream */
20 while (fgets(str, MAX_STR, fp) != NULL) {
21 printf("%s", str);
24 /* Close pipe stream */
25 ret = pclose(fp);
26 if (ret == -1) {
27 errx(EXIT_FAILURE, "pclose()");
29 else {
31 * Use macros described under wait() to inspect the return value
32 * of pclose() in order to determine success/failure of command
33 * executed by popen().
36 if (WIFEXITED(ret)) {
37 printf("Child exited, ret = %d\n", WEXITSTATUS(ret));
38 } else if (WIFSIGNALED(ret)) {
39 printf("Child killed, signal %d\n", WTERMSIG(ret));
40 } else if (WIFSTOPPED(ret)) {
41 printf("Child stopped, signal %d\n", WSTOPSIG(ret));
43 /* Not all implementations support this */
44 #ifdef WIFCONTINUED
45 else if (WIFCONTINUED(ret)) {
46 printf("Child continued\n");
48 #endif
49 /* Non standard case -- may never happen */
50 else {
51 printf("Unexpected return value, ret = 0x%x\n", ret);
55 return EXIT_SUCCESS;