poll(2)不会清空事件队列 [英] poll(2) doesn't empty the event queue

查看:216
本文介绍了poll(2)不会清空事件队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Linux作为编程平台.我正在使用poll(2)知道我的设备是否正在触发事件.

I'm using Linux as my programming platform. I am using poll(2) to know if my device is triggering an event.

第一次调用poll没问题;它阻止并等待事件发生.但是在第二个poll函数调用中,它将返回;但它捕获了事件.下面是我的代码.

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.

您认为出了什么问题?

谢谢.

推荐答案

很明显,如果您正在轮询传入的数据,则应该消耗可用数据(调用read()),否则它将仍然存在并且轮询将立即返回.对称地,POLLOUT确实不需要任何操作,但是您通常希望尽快调用下一个write().因此,根据经验,POLLIN->阅读,POLLOUT->写.

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.

在再次调用poll之前,您还应该重置pollfd结构.

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).

在生产代码中,您还必须检查返回值,因为轮询可能由于预期事件(例如信号)以外的其他原因而中断.然后,您通常想再次调用它,而不是读取不可用的数据(提醒一下,轮询返回值是事件数,0超时,-1一些错误,其错误号为errno).

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).

也可能发生提供给民意测验的文件描述符错误.它们不会使poll返回错误,但会在该文件描述符的pollfd结构的revent字段中设置POLLERR,POLLHUP或POLLNVAL.如果设置了这些事件,则调用read会返回一些错误代码,您可以检查这些错误代码.

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.

这篇关于poll(2)不会清空事件队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆