Recently, we have been dealing with data communication between multiple processes (basically one server and multiple clients), and the communication data is video data, which is large in size and has been weighed repeatedly, decide to use FIFO for processing.
An exclusive FIFO queue is used between the server and each client, which causes blocking. However, you can add O_NONBLOCK to set it to a non-blocking status.
The following is a test program written by me, including the client and server, and a separate fifo famous pipeline between the server and each client.
Client:
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <limits.h>
- #include <time.h>
-
- int main(int argc,char** argv){
- int fd;
- int len;
- char buf[PIPE_BUF];
- time_t tp;
- if(argc!=2){
- printf("Usage:client [Name]");
- }
- if((fd = open(argv[1],O_WRONLY))<0){
- perror("open");
- exit(EXIT_FAILURE);
- }
- while(1){
- time(&tp);
- len = sprintf(buf,"wrfifo: %d sends %s",getpid(),ctime(&tp));
- if((write(fd,buf,len+1))<0){
- perror("write");
- close(fd);
- exit(EXIT_FAILURE);
- }
- }
- close(fd);
- exit(EXIT_SUCCESS);
- }
Server:
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <limits.h>
- //#define PIPE_BUF 8192
- int main(void){
- int fd1,fd2;
- int dumy1,dumy2;
- int len1,len2;
- char buf1[PIPE_BUF],buf2[PIPE_BUF];
- mode_t mode = 0666;
- unlink("fifo1");
- unlink("fifo2");
- if((mkfifo("fifo1",mode))<0){
- perror("mkfifo1");
- exit(EXIT_FAILURE);
- }
- if((mkfifo("fifo2",mode))<0){
- perror("mkfifo2");
- exit(EXIT_FAILURE);
- }
- printf("open fifo1\n");
- if((fd1=open("fifo1",O_RDONLY|O_NONBLOCK))<0){
- // if((fd1=open("fifo1",O_RDONLY,0))<0){
- perror("open1");
- exit(EXIT_FAILURE);
- }
- printf("open fifo2\n");
- if((fd2=open("fifo2",O_RDONLY|O_NONBLOCK))<0){
- // if((fd2=open("fifo2",O_RDONLY,0))<0){
- perror("open2");
- exit(EXIT_FAILURE);
- }
- printf("loop\n");
- while(1){
- len1 = read(fd1,buf1,PIPE_BUF-1);
- if(len1>0)
- printf("rdfifo1 read: %s",buf1);
- len2 = read(fd2,buf2,PIPE_BUF-1);
- if(len2>0)
- printf("rdfifo2 read: %s",buf2);
- }
- close(fd1);
- close(fd2);
- printf("exit\n");
- exit(EXIT_SUCCESS);
- }
Compile the above program
Run./server./client ikeo1./client ikeo2 on the three Super terminals respectively.
If the O_NONBLOCK parameter in the open parameter in server. c is removed, the server program will be blocked in the first open operation!
One disadvantage of FIFO is that the pipe name must be negotiated between the server and the client.
This article is from the Scalpel00 blog, please be sure to keep this source http://scalpel00.blog.51cto.com/1071749/278019