1、mkfifo() 函数 创建管道文件的节点
2、open()函数 在内核创建管道空间,库<fcntl.h>
read()
write()
3、fork() 函数 父子进程,库<sys/types.h>
代码 - - mkfifo()创建管道文件节点
1 #include <stdio.h>
2
3 int main()
4 {
5 int ret;
6 //管道文件、字符设备、块设备、套接字 只有文件节点,不占磁盘空间
7 ret = mkfifo("./myfifo",0777); //mkfifo()只是创建了管道文件节点,并没有在内核空间创建管道空间
8 //mkfifo()创建管道节点;open()在内核创建管道空间
9 if(ret < 0)
10 {
11 printf("myfifo create failure.\n");
12 return -1;
13 }
14
15 printf("myfifo create success.\n");
16 return 0;
17 }
代码 - - open()在内核创建管道空间
1 #include <stdio.h>
2 #include <sys/types.h> //fork()
3 #include <fcntl.h> //open()、write()、read()
4
5 int main()
6 {
7 pid_t pid; //进程号
8 int process_inter = 0;
9 int process_inter_bak = 0;
10
11 pid = fork(); //创建父子进程
12 if(pid == 0) //子进程
13 {
14 int i = 0;
15 int fd2;
16 fd2 = open("./myfifo",O_RDONLY); //在内核创建管道空间
17 read(fd2, &process_inter_bak, 4); //读取管道
18 close(fd2);
19 while(process_inter_bak == 0);
20 for(i = 0; i < 5; i++)
21 {
22 printf("this is child process i = %d\n",i);
23 usleep(100);
24 }
25 }
26 if(pid > 0) //父进程
27 {
28 int i = 0;
29 int fd1;
30 for(i = 0; i < 5; i++)
31 {
32 printf("parent process i = %d\n",i);
33 usleep(100);
34 }
35 process_inter = 1;
36 fd1 = open("./myfifo",O_WRONLY);
37 write(fd1, &process_inter, sizeof(process_inter)); //写入管道
38 while(1);
39 close(fd1);
40 }
41
42 return 0;
43 }
执行: