I'm using Linux as my programming platform. I am using poll(2)
to know if my device is triggering an event.
The first call of poll
is ok; it blocks and waits for the event to happen. But in the second poll
function call, it will return; but it captures the event. Below is my code.
ret = poll( fds, 1, 2000); //2 secs timeout
if( fds[0].revents & POLLIN && ret > 0)
{
printf("event occur\n");
}
It seems the queue/buffer is not empty. I'm just assuming.
What do you think is the problem?
Obviously if you are polling incoming data you should consume available data (calling read()) or it will still be there and poll will return immediately. Symmetrically no operation is really necessary for POLLOUT, but you usually want to call the next write() as soon as possible. So as a rule of thumb POLLIN -> read, POLLOUT -> write.
You should also reset you pollfd struct before calling poll again.
fds[0].fd = sck;
fds[0].events = POLLIN;
fds[0].revents = 0;
ret = poll( fds, 1, 2000); //2 secs timeout
if( fds[0].revents & POLLIN && ret > 0)
{
printf("event occur\n");
}
If you do not reset it each time, garbage from previous call can change poll behavior (well, not really, this is just a portability issue).
In production code you must also check for return value, as poll may have been interrupted for another reason than the expected event (like a signal). Then you usually want to call it again instead of reading data that is not available (as a reminder the poll return value is the number of events, 0 timeout, -1 some error, whose number is in errno).
Errors on files descriptors provided to poll may also occur. They will not make poll return an error but will set POLLERR, POLLHUP or POLLNVAL in the revent field of the pollfd structure for that file descriptor. If these events are set calling read will return some error code that you can check.
if you have an POLLIN event, which means "There is data to read" - do you call some read()
function on your fd before poll()
'ing again ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With