How to do it…

  1. Define an array of size 2.
  2. Invoke the pipe function to connect the two processes and pass the array we defined previously to it.
  3. Invoke the fork function to create a new child process.
  4. Enter the message that is going to be written into the pipe. Invoke the write function using the newly created child process.
  5. The parent process invokes the read function to read the text that's been written into the pipe.

The pipedemo.c program for writing into the pipe through a child process and reading from the pipe through the parent process is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define max 50

int main()
{
char wstr[max];
char rstr[max];
int pp[2];
pid_t p;
if(pipe(pp) < 0)
{
perror("pipe");
}
p = fork();
if(p >= 0)
{
if(p == 0)
{
printf ("Enter the string : ");
gets(wstr);
write (pp[1] , wstr , strlen(wstr));
exit(0);
}
else
{
read (pp[0] , rstr , sizeof(rstr));
printf("Entered message : %s\n " , rstr);
exit(0);
}
}
else
{
perror("fork");
exit(2);
}
return 0;
}

Let's go behind the scenes.