Inter Process Communication using Named Pipes - Chat Program in C

In this post, we will see a chat program using named pipes (fifo). Pipes are used for communication between processes. The named pipes are fifos. They enable two way communication unlike ordinary pipes. But they are half duplex, i.e. communication can take place only in one direction at a time. The program is in 3 parts: pipe_creation.c, leftTerminal.c and rightTerminal.c.

pipe_creation.c

#include<stdio.h>
void main()


{
int f1,f2;
f1 = mkfifo("pipeA",0666);

if(f1<0)
    printf("\npipeA was not created");
else
    printf("\npipeA created");
 
f2 = mkfifo("pipeB",0666);
   
if(f2<0)
    printf("\npipeB was not created");
else
    printf("\npipeB is created\n");
}

leftTerminal.c

#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
void main()
    {
    char str[256]="start";
    int fifo_write,fifo_read;

    while(strcmp(str,"end")!=0)
    {
 
    fifo_write= open("pipeA",O_WRONLY);
     if(fifo_write<0)
        printf("\nError opening pipe");
        else
        {
        printf("\nEnter text:\n");
        scanf("%s",str);
        write(fifo_write,str,255*sizeof(char));
        close(fifo_write);
        }
    
    fifo_read=open("pipeB",O_RDONLY);
    if(fifo_read<0)
        printf("\nError opening write pipe");
        else
        {
    read(fifo_read,str,255*sizeof(char));
        close(fifo_read);
        printf("\n%s",str);
    
    }
    }
}

rightTerminal.c

#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
void main()
{
    char str[256]="start";
    int fifo_read,fifo_write;
    while(strcmp(str,"end")!=0)
    {
    fifo_read=open("pipeA",O_RDONLY);
    if(fifo_read<0)
        printf("\nError opening read pipe");
        else
        {
        read(fifo_read,str,255*sizeof(char));
        close(fifo_read);
        printf("\n%s",str);
        }

    fifo_write=open("pipeB",O_WRONLY);
    if(fifo_write<0)
        printf("\nError opening write pipe");
    else
        {
        printf("\nEnter text:\n");
        scanf("%s",str);
        write(fifo_write,str,255*sizeof(char));
        close(fifo_write);
     }
    }
}

How to run:
Run pipe_creation.c first. Then close it. Then run leftTerm.c. Without closing it, open a new terminal window and run rightTerm.c. Start typing from leftTerm.c and then in rightTerm.c.

Output :
pipe_creation.c:
pipeA created
pipeB is created








leftTerminal.c 

Enter text:
hi

Hai
Enter text:
fine?

Ya.Sure
Enter text:
end



rightTerminal.c

hi
Enter text:
Hai

fine?
Enter text:
Ya.Sure

end
Enter text:
end




No comments :

Post a Comment