Reputation: 195
I have a program that creates a number of input named pipes for which I must use poll() in order to watch over those pipes and get the information that has been written in them at the time that something has been written in them. I'm very new to polling and I couldn't find many examples that would clearly show how to use poll for multiple file descriptors.
Here is how I wrote the code:
char buffer [1024];
size_t count = 0;
ssize_t = bytes;
while(1)
{
int n = poll(pollFd, number_of_pipes, 3000);
if(n != 0)
{
if (n == -1)
{
perror("poll");
exit(1);
}
for(j = 0; j < number_of_pipes; j++)
{
if(pollFd[j].revents & POLLIN)
{
//read the written pipe
if((bytes = read(fd[j], buffer, sizeof(buffer))) > 0)
count += (size_t) bytes;
}
}
}
}
However, I'm not sure if this the correct way to handle the multiple input pipes while using poll(); since I'm also not sure how to know when the read function have reached the end of the file.
Upvotes: 1
Views: 5724
Reputation: 126203
The code looks ok, if incomplete (you don't show how you set up the pollFd
and fd
arrays). It does ignore the actual data read, just counting the total amount; for a real program you probably want to do something with the data.
A couple of comments
If you change it to read from pollFd[j].fd
instead of fd[j]
, you don't need the redundant fd
array -- the descriptors are necessarily all in the pollFd
array
You don't check for EOF or errors on read -- if read returns 0 or -1, you should remove that entry from the pollFd
array and reduce number_of_pipes
.
Upvotes: 2