

#include <stdio.h> FILE *popen(const char *command, const char *mode);
popen creates a pipe between the calling program and a command
to be executed by the OpenEdition shell. A stream opened by popen
should be closed by pclose.
The arguments are pointers to null-terminated strings.
command is a null-terminated shell command. mode is the I/O
mode, which can be set to these values:
r
FILE pointer returned by popen.
w
FILE pointer returned by popen.
Because open files are shared, you can use a mode of "r" as an
input filter and a mode of "w" as an output filter.
You must define an appropriate feature test macro (_SASC_POSIX_SOURCE or
_POSIX_C_SOURCE) to make the declaration of
popen in <stdio.h> visible.
Note:
A stream opened by popen must be closed by pclose.
popen returns a FILE pointer if successful. popen
returns a NULL pointer if a file or process cannot be created.
popen is defined in accordance with POSIX 1003.2
popen function is used to
invoke the shell sort command to do all the work.
/* This program must be compiled with the posix compiler option */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 500
main(int argc, char *argv[])
{
char linebuf[MAXLINE];
char *cmdbuf;
int cmdlen;
FILE *sort_output;
if (argc < 2) cmdbuf = "sort";
else {
if (argc > 2) fputs("Extraneous arguments ignoredn", stderr);
cmdlen = 5+strlen(argv[1]);
/* Allocate space for sort command. */
cmdbuf = malloc(cmdlen);
if (!cmdbuf) exit(EXIT_FAILURE);
sprintf(cmdbuf, "sort %s", argv[1]); /* Build sort command.*/
}
sort_output = popen(cmdbuf, "r"); /* Read the output of sort.*/
if (!sort_output) {
perror("popen failure");
exit(EXIT_FAILURE);
}
/* Read first sorted line. */
fgets(linebuf, sizeof(linebuf), sort_output);
if (feof(sort_output) || ferror(sort_output)) {
fputs("Input error.n");
pclose(sort_output); /* Close sort process before quitting.*/
exit(EXIT_FAILURE);
}
puts(linebuf); /* Write line to stdout. */
/* Close the sort process. It will probably terminate */
/* with SIGPIPE. */
pclose(sort_output);
exit(EXIT_SUCCESS);
}
pclose, pipe, system
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.