Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

44. Pipes and FIFOs > Talking to a Shell Command via a Pipe: popen()

Talking to a Shell Command via a Pipe: popen()

A common use for pipes is to execute a shell command and either read its output or send it some input. The popen() and pclose() functions are provided to simplify this task.

#include <stdio.h>

FILE *popen(const char *command, const char *mode);

Note

Returns file stream, or NULL on error

int pclose(FILE *stream);

Note

Returns termination status of child process, or -1 on error

The popen() function creates a pipe, and then forks a child process that execs a shell, which in turn creates a child process to execute the string given in command. The mode argument is a string that determines whether the calling process will read from the pipe (mode is r) or write to it (mode is w). (Since pipes are unidirectional, two-way communication with the executed command is not possible.) The value of mode determines whether the standard output of the executed command is connected to the write end of the pipe or its standard input is connected to the read end of the pipe, as shown in Figure 44-4.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint