How it works...

We defined a macro, max, of size of 50, a string, str, of size max, and an array, pp, with size 2 . We will invoke the pipe function to connect 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 and 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.

You will be prompted to enter the first message to be written into the pipe. The text that's entered by you will be assigned to the string variable, str. Invoke the write function and the string in str will be written into the pipe, pp. Repeat the procedure for the second message. The second text that's entered by you will also be written into the pipe.

Obviously, the second text will be written behind the first text in the pipe. Now, invoke the read function to read from the pipe. The text that was entered first in the pipe will be read and assigned to the string variable, str, and is consequently displayed on the screen. Again, invoke the read function and the second text message in the pipe will be read from its read end and assigned to the string variable, str, and then displayed on the screen.

Let's use GCC to compile the readwritepipe.c program, as follows:

$ gcc readwritepipe.c -o readwritepipe

If you get no errors or warnings, this means that the readwritepipe.c program has been compiled into an executable file, readwritepipe.exe. Let's run this executable file:

$ ./readwritepipe
Enter the first message to write into pipe: This is the first message for the pipe
Enter the second message to write into pipe: Second message for the pipe
Messages read from the pipe are as follows:
This is the first message for the pipe
Second message for the pipe

In the preceding program, the main thread does the job of writing and reading from the pipe. But what if we want one process to write into the pipe and another process to read from the pipe?  Let's find out how we can make that happen.