Creating “pipelines” with the C programming language can be a bit more involved than the simple shell example . To create a simple pipe with C, we make use of pipe(), open() and close() system calls. However there is a simpler way: the popen() function. The syntax is given below:
FILE *popen ( char *command, char *type);
This standard library function creates a half-duplex pipeline by calling pipe() internally. It then forks a child process, exec the Bourne shell, and executes the “command” argument within the shell. Direction of data flow is determined by the second argument, “type”. It can be “r” or “w”, for “read” or “write”. It cannot be both! popen() returns the pointer to the new file stream or NULL on failure.
Pipes which are created with popen() must be closed with pclose(). popen() and pclose() share a striking resemblance to the standard file stream I/O functions fopen() and fclose().
int pclose( FILE *stream );
The pclose() function performs a wait4() (waits for process termination) on the process forked by popen(). When it returns, it destroys the pipe and the file stream. Once again, it is synonymous with the fclose() function for normal stream-based file I/O. The pclose() returns wait4() status. If everything is all right it simply returns 0.