[英]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.