OS MANUAL 3
OS MANUAL 3
03
Theory:
Conceptually, a pipe is a connection between two processes, such that the standard output
from one process becomes the standard input of the other process. In UNIX Operating
System, Pipes are useful for communication between related processes(inter-process
communication).
• Pipe is one-way communication only i.e we can use a pipe such that One process write
to the pipe, and the other process reads from the pipe. It opens a pipe, which is an
area of main memory that is treated as a “virtual file”.
• The pipe can be used by the creating process, as well as all its child processes, for
reading and writing. One process can write to this “virtual file” or pipe and another
related process can read from it.
• If a process tries to read before something is written to the pipe, the process is
suspended until something is written.
• The pipe system call finds the first two available positions in the process’s open file
table and allocates them for the read and write ends of the pipe.
Syntax:
#include<unistd.h>
int pipe(int pipefd[2]);
pipefd[1] is the writing end of the pipe. So, the process that wants to send the data should use
this file descriptor.
The program below creates a child process. The parent process will establish a pipe and will send
the data to the child using writing end of the pipe and the child will receive that data and print on
the screen using the reading end of the pipe.
//Q. Program to send a message from parent process to child process using pipe()
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
int fd[2],n;
char buffer[100];
pid_t p;
pipe(fd); //creates a unidirectional pipe with two end fd[0] and fd[1]
p=fork();
if(p>0) //parent
{
printf("Parent Passing value to child\n");
write(fd[1],"hello\n",6); //fd[1] is the write end of the pipe
}
else // child
{
printf("Child printing received value\n");
n=read(fd[0],buffer,100); //fd[0] is the read end of the pipe
write(1,buffer,n);
}
}
How it works?
The parent process create a pipe using pipe(fd) call and then creates a child process using fork().
Then the parent sends the data by writing to the writing end of the pipe by using the fd[1] file
descriptor. The child then reads this using the fd[0] file descriptor and stores it in buffer. Then the
child prints the received data from the buffer onto the screen.
Output