In: Computer Science
Creating a pipe in C language requires simple command which is a s follows.
SYSTEM CALL: pipe();
PROTOTYPE: int pipe( int fd[2] );
RETURNS: 0 on success
-1 on error: errno = EMFILE (no free descriptors)
EMFILE (system file table is full)
EFAULT (fd array is not valid)
NOTE: fd[0] is set up for reading, fd[1] is set up for writing
Design a simple C program using ordinary pipes in which a parent and child processes exchange greeting messages. For example, the parent process may send the message “Hello Child Process”, and the child process may return “Hi Parent Process”. Use UNIX pipes to write this program. You need to have bidirectional behavior in your program for which you will need two pipes.
Idea : We need to implement two way communication between Child and Parent process using Pipe
Approach :
CODE:
#include<stdio.h>
#include<unistd.h>
int main()
{ //Initializing Pipe_A and Pipe_B
int Pipe_A[2], Pipe_B[2];
//Initializing status flags for both Pipes
int return_status_pipe_a, return_status_pipe_b;
int pid;
//Messages That will be exchanged
char parent_msg[30] = "Hello Child Process";
char child_msg[30] = "Hello Parent Process";
//Initializing Buffer variable
char read_msg[30];
//Creating Pipe_A and Checking whether it has been
created or not
return_status_pipe_a=pipe(Pipe_A);
if(return_status_pipe_a == -1)
{
printf("Unable to Create Pipe
A\n");
return 1;
}
//Creating Pipe_B and Checking whether it has been
created or not
return_status_pipe_b=pipe(Pipe_B);
if(return_status_pipe_b == -1)
{
printf("Unable to Create Pipe
B\n");
return 1;
}
pid = fork();
//Parent Process
if(pid !=0)
{ //Disable Child Write
close(Pipe_A[1]);
//Disable Parent Read
close(Pipe_B[0]);
printf("Parent (Writing to
Child) : %s\n",parent_msg);
write(Pipe_B[1], parent_msg,
sizeof(parent_msg));
read(Pipe_A[0],read_msg,sizeof(read_msg));
printf("Parent (Reading from Child)
: %s\n",read_msg);
}
//Child Process
else
{ //Disable Child Read
close(Pipe_A[0]);
//Disabe Parent Write
close(Pipe_B[1]);
read(Pipe_B[0],read_msg,sizeof(read_msg));
printf("Child (Reading from
Parent): %s\n", read_msg);
printf("Child (Writing to Parent):
%s\n",child_msg);
write(Pipe_A[1],child_msg,sizeof(child_msg));
}
return 0;
}
Console Output :