1、管道是一个进程连接数据流到另一个进程的通道,它通常把一个进程的输出通过管道连接到另一个进程的输入,如要列出当前文件下所有命名中有"test"的文件:ls -l | grep test。其中"|"就代表我们在使用管道,它会把"ls -l"的查询结果通过管道,发送给grep,然后执行"grep test"命令后把结构输出到终端
2、无名管道特点:
(1)只能用于具有亲缘关系的进程,父子进程、兄弟进程之间(进程描述符在父进程中创建,子进程能够继承,多个子进程均继承后可以互相通信)
(2)半双工通信(同一时刻,只能对管道进行一种操作)
(3)特殊文件,可以使用文件io函数(read,write),不能使用lseek定位
(4)存在内存(内核缓冲区,非用户缓冲区)中,不用主动删除
(5)基于队列实现,有大小限制
3、代码演示
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main ()
{
int fd[2];
int pid;
char buffer[128];
if(pipe(fd) == -1){ //通过pipe创建一个无名管道,
//并生成fd[0],fd[1];两个文件描述符
//fd[0]:读端,fd[1]:写入端
//pipe返回值为-1表示管道创建失败
printf("Create pipe fialed!\n");
} //判断管道是否生成
pid = fork(); //fork函数创建子进程
//返回值:小于0;表示创建子进程失败
// 等于0:表示是子进程
// 大于0;表示是父进程
if(pid < 0){
printf("Create child pipe fialed!\n");
}else if(pid > 0){
sleep(3); //休眠三秒等待子进程运行
printf("This is father\n");
close(fd[0]); //关闭读端
write(fd[1],"Hello from father",strlen("Hello from father"));
wait(NULL); //收集子进程退出信息
}else{
printf("This is child\n");
close(fd[1]); //关闭写端
read(fd[0],buffer,128); //读管道数据,由于管道中无数据,阻塞等待父进程写入数据
printf("read from father: %s\n",buffer);
exit(0);
}
return 0;
}