[英]How can I distinguish read and write events on the same socket?
我正在使用epoll
来获取有关传入数据的通知。 这并不难,因为epoll_wait()
返回的所有事件都表明,我可以从epoll_event.data.fd
(套接字描述符)中读取数据。
但现在我想得到两种类型的通知:接收和发送(套接字可用于发送)。 但我不能这样做是因为:
epoll_event.events
epoll_wait()
返回的epoll_wait()
与我在epoll_ctl()
传递的相同。 所以它在我的例子中包含EPOLLIN
和EPOLLOUT
。 epoll
添加一个套接字(作为EPOLLIN和EPOLLOUT事件),我将得到一个EEXIST
。 每次收到通知时,如果不手动调用select()
如何解决此问题?
man epoll_wait
明确指出“事件成员将包含返回的事件位字段。” 因此,如果你得到EPOLLIN | EPOLLOUT
EPOLLIN | EPOLLOUT
中的epoll_event.events
,那么你的套接字必须准备好进行读写。
如果您只想在套接字更改状态时收到通知,请使用EPOLLET
进行边沿触发操作。
使用epoll_ctl
添加描述符时,将events
mask设置为EPOLLIN | EPOLLOUT
EPOLLIN | EPOLLOUT
。
当您通过epoll_wait
收到通知时,您将循环检索EPOLLIN
和EPOLLOUT
的返回通知。
伪代码 :
int index, count;
count = epoll_wait(epfd, epoll_event, MAX_EVENTS, -1);
for (index = 0; index < count; ++index) {
if (epoll_event[index].events & EPOLLIN) {
// Ready for read
}
if (epoll_event[index].events & EPOLLOUT) {
// Ready for write
}
}
有些人只有在发送缓冲区中存在数据时才设置EPOLLOUT
位。 我没有包含任何错误检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.