簡體   English   中英

如何區分同一套接字上的讀寫事件?

[英]How can I distinguish read and write events on the same socket?

我正在使用epoll來獲取有關傳入數據的通知。 這並不難,因為epoll_wait()返回的所有事件都表明,我可以從epoll_event.data.fd (套接字描述符)中讀取數據。

但現在我想得到兩種類型的通知:接收和發送(套接字可用於發送)。 但我不能這樣做是因為:

  1. epoll_event.events epoll_wait()返回的epoll_wait()與我在epoll_ctl()傳遞的相同。 所以它在我的例子中包含EPOLLINEPOLLOUT
  2. 此外,如果我試圖兩次在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收到通知時,您將循環檢索EPOLLINEPOLLOUT的返回通知。

偽代碼

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM