管道的概念
管道是单向的、先进先出的,它把一个进程的输出和另一个进程的输入连接在一起。
管道的分类
管道包括无名管道和有名管道两种,前者用于父进程和子进程间的通信,后者可用于运行于同一系统中的任意两个进程间的通信。
读写端口
一个进程(写进程)在管道的尾部写入数据,另一个进程(读进程)从管道的头部读出数据。管道提供了简单的流控制机制,进程试图读空管道时,进程将阻塞。同样,管道已经满时,进程再试图向管道写入数据,进程将阻塞
无名管道通信过程
创建管道pipe
读管道read
写管道write
关闭管道close
函数pipe
函数作用:创建无名管道
函数原型:int pipe(int fds[2]);
函数参数:fds:文件描述符 fds[0]用于读管道 fds[1]用于写管道
返回值 :成功:返回0 失败:返回-1
头文件 :#include<unistd.h>
Pipe.c
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int pipe_fd[2];//定义文件描述符数组
if(pipe(pipe_fd)<0)
{
printf("pipe create error\n");
return -1;
}
else
{
printf("pipe create success\n");
}
close(pipe_fd[0]);//关闭读端口
close(pipe_fd[1]);//关闭读端口
}
无名管道用于在父子进程之间通信,通常先创建一个管道,再通过fork函数创建一个子进程,该子进程会继承父进程所创建的管道
必须在系统调用fork( )前调用pipe( ),否则子进程将不会继承文件描述符
Pipe——rw.c
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int pipe_fd[2];//定义文件描述符
pid_t pid;
char buf_r[100];//读缓存
int r_num;//读出来的数据个数
memset(buf_r,0,sizeof(buf_r));//清空缓存区
/*创建无名管道*/
if(pipe(pipe_fd)<0)
{
printf("pipe create error\n");
return -1;
}
/*创建子进程*/
if((pid=fork()) == 0) //子进程
{
printf("\n");
close(pipe_fd[1]);//关闭写端口
sleep(2); //休眠2s是为了等待父进程写入
r_num = read(pipe_fd[0],buf_r,100);
if(r_num > 0)
{
printf("%d numbers read from the pipe is %s\n",r_num,buf_r);
}
close(pipe_fd[0]);//关闭读端口
exit(0);
}
else if(pid > 0)//父进程
{
close(pipe_fd[0]);//关闭读端口
if(write(pipe_fd[1],"Hello",5) != -1)
printf("parent write1 Hello!\n");
if(write(pipe_fd[1]," Pipe",5) != -1)
printf("parent write2 Pipe!\n");
close(pipe_fd[1]);
sleep(3);
waitpid(pid,NULL,0); /*等待子进程结束*/
exit(0);
}
return 0;
}
管道与文件的区别
1.管道通讯是单向的,有固定的读端和写端。
2.数据被进程从管道读出后,在管道中该数据就不存在了,而文件会保存数据。
3.当进程去读取空管道的时候,进程会阻塞,文件为空时返回也为空
4.当进程往满管道写入数据时,进程会阻塞,文件没有容量限制
5.管道容量为64KB(#define PIPE_BUFFERS 16 include/linux/pipe_fs_i.h)