One disadvantage of the anonymous pipeline is that there is no name, so it can only be used for inter-process communication with affinity. After the named pipe (FIFO) is presented, the limit is overcome. FIFO differs from pipe in that it provides a path name associated with it, which exists in the file system as a FIFO file. A named pipe is a device file, so even if the process does not have a affinity to the process that created the FIFO, it can communicate with each other as long as it has access to the path.
FIFO always works according to the first-in-one-out principle, the first written data will be read out of the pipeline first.
There are two ways to create a FIFO under Linux, one is to build a named pipe under the shell, and the other is to use a system function in the program.
Here we use the system function Mkfifo to establish in the program:
1): Create a named pipe on the write end and open it in write-only mode under the same path;
2): Open the file in read-only mode with the same path as the reader;
FIFO Read side:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main ()
{
int Fd=open ("./.tmp", o_rdonly);
if (fd<0) {
Perror ("open");
Exit (1);
}
Char buf[1024];
memset (buf, ' n ', sizeof (BUF));
while (1)
{
ssize_t _size=read (fd,buf,sizeof (BUF));
if (_size<=0)
{
Perror ("read");
Exit (2);
}
printf ("%s\n", buf);
}
return 0;
}
FIFO Write end:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main ()
{
int _fifo=mkfifo ("./.tmp", S_ififo | 0666);
if (_fifo<0)
{
Perror ("Mkfifo");
Exit (1);
}
int Fd=open ("./.tmp", o_wronly);
if (fd<0) {
Perror ("open");
Exit (2);
}
Char buf[1024];
while (1)
{
memset (buf, ' n ', sizeof (BUF));
printf ("You want to say:");
Gets (BUF);
Fflush (stdout);
ssize_t _size=write (Fd,buf,strlen (BUF));
if (_size>0)
{
buf[_size]= ' + ';
}else{
Perror ("write");
Exit (3);
}
}
return 0;
}
The result of its operation:
Write End:
You want to Say:nihao
You want to Say:jin Tian Tian Qi Zhehao
You want to Say:ni Zai NA
You want to say:
Read the end:
Nihao
Jin Tian Tian Qi Zhehao
Ni Zai na
Thus, the path names in the file system are global and can be accessed by each process, so the path names in the file system are used to identify an IPC channel. And its behavior is similar to the previously spoken no name pipe. Because of all the files under the LINUC, the use of the named pipe becomes very uniform with the file operation, makes it very convenient to use, and we can use it as usual file name in the command.
This article is from the "fringe" blog, so be sure to keep this source http://ab6107.blog.51cto.com/10538332/1762358
Named Pipes for interprocess communication under Linux (FIFO)