#include <stdio.h>
#include"common.h"
/*
* 无名管道通信:
* 1.不支持多人写入,写入不保护
* 2.用于1对1通信
* 3.fd[0]为读端 fd[1]为写端
* 4.阻塞等待
*
*/
int main()
{
//1.创建无名管道
int fd[2];
pipe(fd);
//2.创建子进程
pid_t pid = fork();
if(pid<0)//进程创建失败
{
printf("fork failed\n");
exit(1);
}
else if(pid>0)//父进程
{
close(fd[1]); //关闭父进程的写入权限,防止子进程结束后自己当读写者导致阻塞等待
char buf[20]; //准备好buf
bzero(buf,sizeof(buf)); //清空buf
read(fd[0],buf,sizeof(buf)); //读取管道中的数据放入buf中
printf("收到子进程的消息:%s\n",buf);
}
else//子进程
{
write(fd[1],"hello",10); //写数据进管道中
}
return 0;
}
This picture is the read and write characteristics of the pipeline