The Linux Programming Interface

(nextflipdebug5) #1
Pipes and FIFOs 905

t fp = popen(popenCmd, "r");
if (fp == NULL) {
printf("popen() failed\n");
continue;
}


/* Read resulting list of pathnames until EOF */

fileCnt = 0;
while (fgets(pathname, PATH_MAX, fp) != NULL) {
printf("%s", pathname);
fileCnt++;
}

/* Close pipe, fetch and display termination status */

status = pclose(fp);
printf(" %d matching file%s\n", fileCnt, (fileCnt != 1)? "s" : "");
printf(" pclose() status == %#x\n", (unsigned int) status);
if (status != -1)
printWaitStatus("\t", status);
}

exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––– pipes/popen_glob.c
The following shell session demonstrates the use of the program in Listing 44-5. In
this example, we first provide a pattern that matches two filenames, and then a pat-
tern that matches no filename:

$ ./popen_glob
pattern: popen_glob* Matches two filenames
popen_glob
popen_glob.c
2 matching files
pclose() status = 0
child exited, status=0
pattern: x* Matches no filename
0 matching files
pclose() status = 0x100 ls(1) exits with status 1
child exited, status=1
pattern: ^D$ Type Control-D to terminate

The construction of the command qr for globbing in Listing 44-5 requires some
explanation. Actual globbing of a pattern is performed by the shell. The ls command
is merely being used to list the matching filenames, one per line. We could have
tried using the echo command instead, but this would have had the undesirable
result that if a pattern matched no filenames, then the shell would leave the pattern
unchanged, and echo would simply display the pattern. By contrast, if ls is given the
name of a file that doesn’t exist, it prints an error message on stderr (which we dis-
pose of by redirecting stderr to /dev/null), prints nothing on stdout, and exits with a
status of 1.
Free download pdf