Spread the love

2. Named PIPE (FIFO’s) :

Drawbacks of PIPE :

1.In PIPE communication, only intra-communication between processes is possible i.e. related processes only.

2.Scope of the PIPE is temporary i.e. only upto the program is running.

3.We have to handle file descriptors for communication between two processes.

So, the next inter process communication mechanism is Named PIPE (FIFO).

You can create named pipes from the command line and from within a program.

The preferred command-line method is to use-

# mkfifo filename

From inside a program, you can use two different calls:

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

Note: Named Pipes(FIFO) are used for communication between related and unrelated processes on the sane LINUX machine.

fifo1

EXAMPLE :

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

int main()
{
	int res,fd;
	char str[50],str1[50];
	if(access("my_fifo",F_OK)==-1)
	{
		printf("\nFile Permission Are OK\n");
		res=mkfifo("my_fifo",0777);
		if(res==-1)
		{
			perror("\nFifo Can't Created\n");
			exit(1);
		}
	}
	printf("\nFifo Created Successfully...\n");
	fd=open("my_fifo",O_RDWR);
	if(fd==-1)
	{
		perror("\nFifo Can't Open..\n");
		exit(1);
	}
	else
	{
		printf("\nEnter Data To Be Written..\n");
		//scanf("%s",str);
		gets(str);
		res=write(fd,str,sizeof(str));
		if(res<0)
		{
			perror("\nWrite Error..\n");
			exit(1);
		}
		else
		{
			printf("\nWritten Successfully.\n");
		}
		lseek(fd,0,SEEK_SET);
		res=read(fd,str1,sizeof(str1));
		if(res<0)
		{
			printf("\nRead Error....\n");
			exit(1);
		}
		else
		{
			printf("\nData From Named Pipe Is:%s\n",str1);
		}
	}
}

 

OUTPUT :

File Permissions Are OK

Fifo Created Successfully…

Enter Data To Be Written..

Hello Linux

Written Successfully…

Data From Named Pipe Is:Hello Linux