管道

  管道linux支持最初unix IPC 形式之一,具有以下特点,管道是半双工的,数据只能想一个方向流动,需要双方通信是,需要建立两个管道, 管道有分为无名管道,命名管道;

  一:无名管道

    无名管道是通过函数pipe()创建,它返回的是一个二位数组类型,【0】端为读端,【1】端为写端

    下面是无名管道实现代码:

    子进程在【1】端写数据,父进程在【0】读数据

 1 #include <stdio.h>
 2 #include <fcntl.h>
 3 #include <stdlib.h>
 4 #include <unistd.h>
 5 
 6 int main()
 7 {
 8     int fd[2];
 9     int ret = 0;
10     pid_t pid = 0;
11     
12     ret = pipe(fd);
13     if(ret < 0) {
14         perror("pipe");
15         exit(EXIT_FAILURE);
16     }
17     
18     pid = fork(); //创建一个子进程    
19     if(pid < 0) {
20         perror("fork");
21         exit(EXIT_FAILURE);
22     }
23     
24     //子进程在【1】端写
25     if(pid == 0) {
26         ret = write(fd[1], "this is child
", 15);
27         if(ret < 0) {
28             perror("write");
29             exit(EXIT_FAILURE);
30         }
31         close(fd[0]);        
32     }
32
34     if(pid > 0) {
35         char data[20] = {0};
36         ret = read(fd[0], data, 15);
37         if(ret < 0) {
38             perror("read");
39             exit(EXIT_FAILURE);
40         }
41         printf("data is: %s
", data);
42         close(fd[1]);
43         wait(NULL);
44     }    
45 }

  二:下面是命名管道

  命名管道通过mkfifo创建一个管道文件,对文件进行读写操作

  实现过程如下:

 1 /*
 2  *有名管道就是通过mkfifo开创一个管道文件
 3  *对文件来进行读写操作
 4  * */
 5 #include <stdio.h>
 6 #include <signal.h>
 7 #include <stdlib.h>
 8 #include <fcntl.h>
 9 
10 int main()
11 {
12     int ret  = 0;
13 #if 0
14     //创建一个管道文件
15     ret = mkfifo("myfifo", 0644);
16     if(ret < 0) {
17             perror("mkfifo error");
18             exit(EXIT_FAILURE);
19         }
20 #else
21 
22 #endif
23 
24     int fd = open("myfifo", O_RDWR);
25     if(fd < 0) {
26         perror("open");
27         exit(EXIT_FAILURE);
28     }
29     
30     ret = write(fd, "hello world bunfly", 18);
31     if(ret < 0) {
32         perror("write");
33         exit(EXIT_FAILURE);
34     }
35         
36     char buf[20] = {0};
37     ret = read(fd, buf, 18);
38     if(ret < 0) {
39         perror("read");
40         exit(EXIT_FAILURE);
41     }    
42 
43     printf("buf is: %s
", buf);
44     close(fd);
45     return 0;
46 }
原文地址:https://www.cnblogs.com/wenqiang/p/4745421.html