pipe函数有关阻塞问题

注:pipe函数创建无名管道

1、pipe函数读阻塞

#include <stdio.h>
#include <unistd.h>
int main()
{
int fd[2];
int ret;
char read_buf[128] = {0};
char write_buf[] = "hello linux\n";
ret = pipe(fd);
if(ret < 0)
{
perror("create pipe failed\n");
return -1;
}
printf("fd[0] = %d,fd[1] = %d \n",fd[0],fd[1]);
write(fd[1],write_buf,sizeof(write_buf));
read(fd[0],read_buf,128);   //此时读过之后,无名管道便为空的,当再次读时,则会阻塞
printf("read data from pipe %s",read_buf);

printf("second read before \n");
read(fd[0],read_buf,128);
printf("second read after \n");
close(fd[0]);
close(fd[1]);
return 0;
}

2、pipe函数写阻塞

#include <stdio.h>
#include <unistd.h>
int main()
{
int fd[2];
int i;
int ret;
char read_buf[128] = {0};
char write_buf[] = "hello linux\n";
ret = pipe(fd);
if(ret < 0)
{
perror("create pipe failed\n");
return -1;
}
printf("fd[0] = %d,fd[1] = %d \n",fd[0],fd[1]);
i =0;
while(i < 5041)
{   
write(fd[1],write_buf,sizeof(write_buf));  //此时因为只有写,而没有读,因此便阻塞在了下一步读,要解决这个问                    //read(fd[0],read_buf,128);                                                            //题,只需加上这两句代码即可
 //printf("read data from pipe %s",read_buf);
i++;
}
return 0;
}



猜你喜欢

转载自blog.csdn.net/xiaonan153/article/details/80046620