管道文件是一个特殊文件,它由队列实现的。在文件IO中,创建、打开一个文件是由open函数实现,但是无名管道不能用open创建,对应的函数是pipe。
无名管道读完就删除,再读就阻塞;缓存满了,也会阻塞。只能在父子进程(有亲缘关系的进程)间通信。
pipe函数: 创建管道
函数原型:int pipe(int fd[2]);
头文件:unistd.h
参数:文件描述符。fd[0]是读端口,fd[1]是写端口。
返回:成功0,出错-1.
例:int ret=pipe(int fd[2]);
write函数 文件IO写
函数原型:write(intfd, void *buf, size_t count ):
参数:intfd,向哪一个文件中去写
buf,向这个文件中写什么内容
count,向这个文件中写多少个
返回值:是实际写的字节数。
例:write(fd[1],writebuf,sizeof(writebuf));
read函数: 文件IO读
函数原型:read(intfd, void *buf, size_t count)
参数:intfd,向哪一个文件中去读
buf,读到什么地方去
count,读多少个
返回值:是实际读的字节数
例:read(fd[0],readbuf,128);
通过无名管道,父进程先执行,子进程后执行。
先pipe再fork,子进程继承父进程的文件描述符,所以可以父子进程间通信。
#include "unistd.h"
#include "stdio.h"
#include "sys/types.h"
#include "stdlib.h"
int main()
{
pid_t pid