Define a macro max, of size 50 and two string variables, wstr and rstr, of size max. The wstr string will be used for writing into the pipe and rstr will be used for reading from the pipe. Define an array, pp, of size 2, which will be used for storing the file descriptors of the read and write ends of the pipe. Define a variable, p, of the pid_t data type, which will be used for storing a process ID.
We will invoke the pipe function to connect the two processes and pass the pp array to it. The index location pp[0] will get the file descriptor for the reading end of the pipe, while pp[1] will get the file descriptor for the write end of the pipe. The program will exit if the pipe function does not execute successfully.
Then, we will invoke the fork function to create a new child process. You will be prompted to enter the message to be written into the pipe. The text you enter will be assigned to the string variable wstr. When we invoke the write function using the newly created child process, the string in the wstr variable will be written into the pipe, pp. Thereafter, the parent process will invoke the read function to read the text that's been written into the pipe. The text that's read from the pipe will be assigned to the string variable rstr and will consequently be displayed on the screen.
Let's use GCC to compile the pipedemo.c program, as follows:
$ gcc pipedemo.c -o pipedemo
If you get no errors or warnings, this means that the pipedemo.c program has been compiled into an executable file, pipedemo.exe. Let's run this executable file:
$ ./pipedemo
Enter the string : This is a message from the pipe
Entered message : This is a message from the pipe
Voila! We've successfully communicated between processes using pipes. Now, let's move on to the next recipe!