Sometimes it's useful to redirect the output (stdout for example) of a child process to the parent process. This tutorial shows how to redirect the stdout of the child process to a pipe which the parent process is reading.
This walkthrough only shows the important stuff.
The pipe file descriptors have to be known to the parent as well as to the child process, therefore we'll declare it in the global space.
The child and parent codes are separated in functions. Let's have a look at the child code first.
We close the end of the pipe, that we never need: the reading end.
Now we have to close stdout (file descriptor 1) and redirect it to the pipe.
18 19 20
To demonstrate that stdout is redirected now, let's print out some text:
The parent process is not very spectacular, business as usual. It defines a buffer (line 32), closes the write-end of the pipe (not used, line 38) and reads from the pipe until the other end gets closed (line 42). The output is written to
stdout (line 44). Remember we only redirected it within the context of the child process. Within the context of the parent process, stdout remains unchanged.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
The function main is rather boring. Just the usual fork stuff we have seen in previous tutorials. Therefore the code is noth shown here.
Compilation and execution is very easy since you don't need any special library.
To compile use the following command:
$ gcc -o process4 process4.c
To execute is just as easy as to compile:
All source code files provided by this page is free to copy, modify, redistribute and use for any purpose. The tutorial is copyrighted by Mario Konrad.