FIFO solves the problem of generating a large number of temporary files when the process communicates, and can achieve communication between non-consanguinity processes, and can be reserved for later process use.
The read and write rules for FIFO are similar to those for anonymous pipelines, butFIFO is saved on disk, while anonymous pipes are stored in memory.
When the FIFO write process is closed, a file terminator is sent to the FIFO read process.
Client:
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
int main()
{
char* msg = "Hello, i am client!\n";
int fd = open("./fifo1",O_WRONLY);
int i = 0;
for(;i<10;i++)
{
printf(msg);
if(write(fd,msg,strlen(msg)+1)<0)
{
_exit(-1);
}
sleep(2);
}
close(fd);
return 0;
}
Server-side:
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
int main()
{
int fd = open("./fifo1",O_RDONLY);
int i = 0;
char buf[24]={0};
while(read(fd,buf,24)>0)
{
printf(buf);
}
close(fd);
return 0;
}
From for notes (Wiz)
FIFO for client server-side communication