C program which demonstrates interprocess communication between a reader process and a writer process

Fifo file:
It is a special pipe device file which provides a temporary buffer for two or more processes to communicate by writing data to and reading data from the buffer. The size of the buffer is fixed to PIPE_BUF. Data in the buffer is accessed in a first-in-first-out manner. The buffer is allocated when the first process opens the FIFO file for read or write. The buffer is discarded when all processes close their references (stream pointers) to the FIFO file. Data stored in a FIFO buffer is temporary.

The prototype of mkfifo is:

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int mkfifo(const char *path_name, mode_t mode);

open:
This is used to establish a connection between a process and a file i.e. it is used to open an existing file for data transfer function or else it may be also be used to create a new file. The returned value of the open system call is the file descriptor (row number of the file table), which contains the inode information.
The prototype of open function is,
#include<sys/types.h>
#include<sys/fcntl.h>
int open(const char *pathname, int accessmode, mode_t permission);

read:
The read function fetches a fixed size of block of data from a file referenced by a given file descriptor.

The prototype of read function is:
#include<sys/types.h> #include<unistd.h>
size_t read(int fdesc, void *buf, size_t nbyte);

write:
The write system call is used to write data into a file. The write function puts data to a file in the form of fixed block size referred by a given file descriptor.

The prototype of write is
#include<sys/types.h> #include<unistd.h>
ssize_t write(int fdesc, const void *buf, size_t size);

close:
The close system call is used to terminate the connection to a file from a process.

The prototype of the close is
#include<unistd.h>
int close(int fdesc);

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

int main(int argc, char* argv[])
{
int fd;
char buf[256];
if(argc != 2 && argc != 3)
{
printf("USAGE %s  []\n",argv[0]);
return 0;
}
mkfifo(argv[1],S_IFIFO | S_IRWXU | S_IRWXG | S_IRWXO );
if(argc == 2)
{
fd = open(argv[1], O_RDONLY|O_NONBLOCK);
while(read(fd, buf, sizeof(buf)) > 0)
printf("%s",buf);
}
else
{
fd = open(argv[1], O_WRONLY);
write(fd,argv[2],strlen(argv[2]));
}
close(fd);
}

FacebookTwitterEmailWhatsAppShare

				
			

Leave a Reply