Redirecting I/O Programmatically

Last week, I showed you how to redirect a program's input or output from

the command line. Today, we will see how to accomplish the same task


The popen() Syscall

The system() command launches a new child process allowing it to read

from the standard input and write to the standard output. However, in

many cases, you want the child process to read input from the parent

process or direct its output to the parent process instead of the

standard output. The popen() syscall enables you to achieve this:

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

The first parameter is the command the name of the executable to be

launched. The second parameter should be "r" if the parent wants to read

the output from child, or "w" if it wishes to write to the child's

standard input (you can't combine both at once with popen()). popen()

returns FILE*, which can be read from or written to, or NULL if the call

fails. Just as with ordinary stdio files, you must close the pipe by

calling pclose() after the I/O operation is completed. In addition, you

should flush the stream after writing to it to prevent delays due to

stdio buffering.

The following program launches a child process called "converter" that

converts Fahrenheit degrees to Celsius. The parent process passes

converter an expression for evaluation and waits for it to evaluate it.

Finally, the parent process closes the pipe and exits too:


#include #include int main() { char buff[1024]={0}; FILE * cvt; int status; /*launch converter and open a pipe through which the parent will write to it */ cvt=popen("converter", "w"); if (!cvt) { printf("couldn't open a pipe; quitting\n"); exit(1) } printf("enter Fahrenheit degrees: " ); fgets(buff, sizeof (buff), stdin); /*read user's input*/ /*send expression to converter for evaluation*/ fprintf(cvt, "%s\n", buff); fflush(cvt); /*close pipe to converter and wait for it to exit*/ status=pclose(cvt); /*check the exit status of pclose()*/ if (!WIFEXITED(status)) printf("error on closing the pipe\n"); return 0; } The important steps in this program are: 1) The popen() call which establishes the association between a child process and a pipe in the parent. 2) The fprintf() call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout. 3) The pclose() call that closes the pipe and causes the child process to terminate.
Top 10 Hot Internet of Things Startups
Join the discussion
Be the first to comment on this article. Our Commenting Policies