一、无名管道
父子之间进行单向通信
假设先父进程先运行,子进程先sleep(6)秒,结果就是read()函数发生了阻塞,因为没有数据给他读
1 #include <string.h>
2 #include<stdio.h>
3 #include<unistd.h>
4 #include <stdlib.h>
5
6 // int pipe(int pipefd[2]);
7
8 int main()
9 {
10 int pipefd[2];
11 if(pipe(pipefd) == -1){
12 perror("why");
13 }
14
15 pid_t pid;
16 pid = fork();
17 if(pid == 0){
18 printf("child\n");
19 sleep(6);
20 close(pipefd[0]);
21 write(pipefd[1],"I wanna go home",16);
22 }else if(pid > 0){
23 printf("father\n");
24 char readBuf[32]={0};
25 close(pipefd[1]);
26 read(pipefd[0],readBuf,16);
27 printf("readBuf context:%s\n",readBuf);
28 }else{
29 perror("why");
30 }
31
32 return 0;
33 }
二、有名管道或命名管道
FIFO创建:
1 #include<stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <errno.h>
5 // int mkfifo(const char *pathname, mode_t mode);
6
7 int main()
8 {
9 if(mkfifo("./file",0600) == -1 && errno!=EEXIST){
10 perror("why");
11 }
12
13 return 0;
14 }
~
~
发数据
1 #include<stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <fcntl.h>
7
8 // int mkfifo(const char *pathname, mode_t mode);
9
10 int main()
11 {
12 int fd = open("./file",O_WRONLY);
13 write(fd,"hello,world",12);
14 printf("write success\n");
15
16 close(fd);
17 return 0;
18 }
读数据
1 #include<stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 // int mkfifo(const char *pathname, mode_t mode);
8
9 int main()
10 {
11 if(mkfifo("./file",0600) == -1 && errno!=EEXIST){
12 perror("why");
13 }
14
15 int fd = open("./file",O_RDONLY);
16 char readBuf[32] ={0};
17 int n_read = read(fd,readBuf,32);
18 printf("read %d byte to readBuf context:%s\n",n_read,readBuf);
19
20 close(fd);
21 return 0;
22 }
=========================================================================
也可以一端一直写,另一端一直读,只要加循环就可以再加sleep(1)