从管道中读数据的特点:
1、默认用read函数从管道中读数据是阻塞的。
2、调用write函数向管道里写数据,当缓冲区已满时write也会阻塞。
3、通信过程中,读端口全部关闭后,写进程向管道内写数据时,写进程会(收到SIGPIPE信号)退出。
注意:
利用无名管道实现进程间的通信,都是父进程创建无名管道,然后再创建子进程,子进程继承父进程的无名管道的文件描述符,然后父子进程通过读写无名管道实现通信。
案例代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<unistd.h>
int main()
{
//创建无名管道
int pipefd[2];
if(pipe(pipefd) == -1)
{
perror("fail to pipe");
exit(1);
}
//使用fork函数创建子进程
pid_t pid;
pid = fork();
if(pid <0)
{
perror("fail to fork");
exit(1);
}
else if(pid > 0)
{
char buf[128] = {};
while(1)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0';
if(write(pipefd[1],buf,sizeof(buf)) == -1)
{
perror("fail to write\n");
exit(1);
}
}
}
else
{
char buf[128] = "";
while(1)
{
if(read(pipefd[0],buf,sizeof(buf)) == -1)
{
perror("fail to read\n");
exit(1);
}
printf("from parent: %s\n",buf);
}
}
return 0;
}
运行结果: