read函数

从文件描述符指向的管道口读入指定字节的字符串到指定的数组中

write函数

从指定的数组中写入指定数量的字节到指定的文件描述符指向的管道口

常见的 三种 0, 1, 2 分别表示标准输入,标准输入,标准错误

pipe函数

dup&dup2函数

复制一份相同的文件描述符

fork函数

在当前父进程创建一个子进程,子进程返回得fpid == 0

文件描述符

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main()
{
char buffer2[100];
char buffer[] = "Let's study pipe!";
int fd[2];
pid_t fpid;
pipe(fd);
fpid = fork();
//printf("%d %d \n", fd[0], fd[1]);
if(fpid < 0){
perror("fork error\n");
}
else if(fpid > 0){
//父进程 向管道中写入数据
close(fd[0]);
write(fd[1], buffer, strlen(buffer) + 1);
printf("father process input buffer in pipe success!\n");

}
else if(fpid == 0){
//子进程 从管道中读出数据
close(fd[1]);
read(fd[0], buffer2, strlen(buffer) + 1);
printf("son process output buffer in pipe success!\n");
printf("the buffer in pipe is %s\n", buffer2);
}
return 0;
}

上述代码的作用位父进程将buffer字符串数据写入管道中,子进程从管道中读入数据到新数组buffer2中

编译输出后

image-20210124180113099

缓冲区

三种缓冲

全缓冲,行缓冲,不缓冲