Detailed explanation of named pipes under linux

1. Named Pipes

Create a named pipe creation method:

Function: mkfifo("my.p", 0644)

Command: mkfifo my.p

Named pipe function: build a buffer in the kernel and name it, so that two unrelated processes can communicate, write and read things through the open buffer. Once the two processes can find the shared buffer, the file my.p can be deleted, and the communication between the two processes will not be affected after deletion .

It should be noted that when only the process writes to this cache (that is, there is no reading process), then the writing process is blocked, and vice versa; therefore, the named pipe must be two processes, one for writing and one for reading, in Linux Below, we can use two terminals to observe.

2.  Cases. There are 3 source files in this case : ( 1 ) create a named pipe ( 2 ) write content to the pipe ( 3 ) read from the pipe.

(1) Create a named pipe:

  1. 1 #include <stdio.h>  
  2.   2 #include <stdlib.h>  
  3.   3 #include <unistd.h>  
  4.   4   
  5.   5  int  main()  
  6.   6 {  
  7.   7     mkfifo("my.p",0644);  
  8.   8     return 0;  
  9.   9 }  

(2) write pipeline

  1. 1 #include <stdio.h>  
  2.   2 #include <stdlib.h>  
  3.   3 #include <unistd.h>  
  4.   4 #include <fcntl.h>  
  5.   5  int  main()  
  6.   6 {  
  7.   7     int fd=open("my.p",O_WRONLY);  
  8.   8     if(fd==-1)  
  9.   9     {  
  10.  10         perror("open failure");  
  11.  11         exit(1);  
  12.  12     }  
  13.  13   
  14.  14     int i=0;  
  15.  15     while(1)  
  16.  16     {  
  17.  17         write(fd,&i,sizeof(i));  
  18.  18         printf("write %d is ok\n",i);  
  19.  19         i++;  
  20.  20         sleep(1);  
  21.  21     }  
  22.  22     return 0;  
  23.  23 }  

(3) Read pipeline

  1. 2 #include <stdio.h>  
  2.  3 #include <stdlib.h>  
  3.  4 #include <unistd.h>  
  4.  5 #include <fcntl.h>  
  5.  6   
  6.  7  int  main()  
  7.  8 {  
  8.  9     int fd=open("my.p",O_RDONLY);  
  9. 10     if(fd==-1)  
  10. 11     {  
  11. 12         perror("open failure");  
  12. 13         exit(1);  
  13. 14     }  
  14. 15   
  15. 16     int i=0;  
  16. 17     while(1)  
  17. 18     {  
  18. 19         read(fd,&i,sizeof(i));  
  19. 20         printf("%d\n",i);  
  20. 21         sleep(1);  
  21. 22     }  
  22. 23     return 0;  
  23. 24 }  

In addition, about anonymous pipes are used for communication with related pipes, created with pipe() , see the next blog for details.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324824112&siteId=291194637