管道读写的几种情况:
first:写端关闭 读端读完管道数据 再次读返回0 相当于读到EOF
second:读端关闭 写端写管道, 收到信号SIGPIPE 导致写进程终止
third:写端没有关闭 读端读完管道数据 再次读 阻塞**
fourth:读端没有读管道数据, 当写端写满管道, 再次写, 阻塞
下面给出这四种情况对应的代码,可直接运行看情况
第一种
写端关闭 读端读完管道数据 再次读返回0 相当于读到EOF
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
/*
*写端关闭 读端读完管道数据 再次读返回0 相当于读到EOF
* */
int main()
{
int fd[2];
if(pipe(fd) < 0)
{
perror("pipe");
exit(1);
}
pid_t pid = fork();
if(pid < 0)
{
perror("fork");
exit(1);
}
else if(pid == 0) //子进程先读
{
close(fd[1]); //关闭无用文件描述符
sleep(2); //确保另一端写管道关闭
char ch;
int n;
while((n = read(fd[0], &ch, 1)))
{
printf("n = %d ", n);