How poll deal with closed pipe
I want to konw:
When a pipe close , what status poll will set for the pipe's file descriptor?
I try the code below, After child process close all file descriptor , the
poll just think all file descriptor can read! Is that right? Or just I
make some mistake in this code?
I use SUSE and gcc .
#include <stdio.h>
#include <unistd.h>
#include "../../../myInclude/apue.h"
#include <sys/poll.h>
int main(int argc, char **argv)
{
int fd1[2]; int fd2[2]; int fd3[2];
pid_t pid;
if(pipe(fd1)<0 ||pipe(fd2)<0 ||pipe(fd3) <0)
err_sys("pipe error");
if((pid = fork()) <0)
err_sys("fork() error");
else if(pid == 0)
{
close(fd1[0]);
close(fd2[0]);
close(fd3[0]);
if(write(fd1[1],"hello fd1 write!",17)!= 17)
err_sys("write 1error ");
sleep(2);
if(write(fd2[1],"hello fd2 write!",17)!=17)
err_sys("write 2error");
sleep(2);
if(write(fd3[1],"hello fd3 write!",17)!= 17)
err_sys("write 3error");
sleep(2);
close(fd1[1]);
close(fd2[1]);
close(fd3[1]);
}
else
{
close(fd1[1]);
close(fd2[1]);
close(fd3[1]);
struct pollfd fd[3];
fd[0].fd = fd1[0];
fd[1].fd = fd2[0];
fd[2].fd = fd3[0];
fd[0].events = POLLIN;
fd[1].events = POLLIN;
fd[2].events = POLLIN;
while(poll(fd,3,3000) >0)
{
printf("now I come \n");
int i = 0,n;
char line[MAXLINE];
for(; i< 3; i++)
{
if(fd[i].revents = POLLIN)
if ((n =read(fd[i].fd,line,MAXLINE))< 0)
err_sys("read error : %d",i);
else
{
line[n] = 0;
printf("read from pipe %d : %s\n",i,line);
}
}
}
close(fd1[0]);
close(fd2[0]);
close(fd3[0]);
}
return 0;
}
No comments:
Post a Comment