27 Program for Inter-Process Communication using message passing mkfifo

Working of Message Passing:
The Sender Process: can use write() system call to write data into the pipe.
The Receiver Process: can use read() system call to read data from the pipe.

FIFO named pipe works in Blocked Mode by default, that is Both reader and writer must be present at the same time.
ex: Teacher will not send any data until students are not present and vice-versa.

Available In:
#include<sys/types.h>
#include<sys/stat.h>

Prototype:
int mkfifo(const char *pathname, mode_t mode);
where,
        pathname: Name of the pipe, that you want to create
                          It will assign to the named pipe.    
        mode_t : Permission you want to give on file read/write/execute

return:
    0 : Successful
    -1 : Failure

Advantage:
This fifo special file can be use by any process for reading or writing just like a 
normal file.

Program create.c :

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>

int main()
{
    int res,res2;

    // creates a named pipe with the name fifo1
    
    res = mkfifo("fifo1",0666);
    res2 = mkfifo("fifo2",0666);

    printf("\n Named Pipe Created");
 
}

Program User1.c :

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>

int main()
{
    int fd;

    char arr1[100],arr2[100];

    while(1)
    {
        fd = open("fifo1",O_WRONLY);
        fgets(arr2,100,stdin);
        write(fd,arr2,strlen(arr2)+1);
        close(fd);

        fd = open("fifo2",O_RDONLY);
        read(fd,arr1,sizeof(arr1));
        printf("User2 : %s\n",arr1);
        close(fd);
    }
}

Program User2.c :

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>

int main()
{
    int fd;

    char str1[100],str2[100];

    while(1)
    {
        fd = open("fifo1",O_RDONLY);
        read(fd,str1,sizeof(str1));
        printf("User1 : %s\n",str1);
        close(fd);

        fd = open("fifo2",O_WRONLY);
        fgets(str2,100,stdin);
        write(fd,str2,strlen(str2)+1);
        close(fd);
    }
}


Output:

1) Creating Named Pipe: create.c

Create Named Pipe

2) User1.c:

Message-Passing-User1



3) User2.c:

Message-Passing-User2


Previous
Next Post »