eventfd with epoll

We can get eventfd linux manual from http://www.man7.org/linux/man-pages/man2/eventfd.2.html

Program sample

eventfd with select/poll(epoll)

The returned file descriptor supports poll(2) (and analogously epoll(7)) and select(2), as follows:

  • The file descriptor is readable (the select(2) readfds argument; the poll(2) POLLIN flag) if the counter has a value greater than 0.

  • The file descriptor is writable (the select(2) writefds argument; the poll(2) POLLOUT flag) if it is possible to write a value of at least "1" without blocking.

  • If an overflow of the counter value was detected, then select(2) indicates the file descriptor as being both readable and writable, and poll(2) returns a POLLERR event. As noted above, write(2) can never overflow the counter. However an overflow can occur if 2^64 eventfd "signal posts" were performed by the KAIO subsystem (theoretically possible, but practically unlikely). If an overflow has occurred, then read(2) will return that maximum uint64_t value (i.e., 0xffffffffffffffff).

epoll_wait()

The epoll_wait() system call waits for events on the epoll(7) instance referred to by the file descriptor epfd. The memory area
pointed to by events will contain the events that will be available for the caller. Up to maxevents are returned by epoll_wait(). The maxevents argument must be greater than zero. The timeout argument specifies the number of milliseconds that epoll_wait() will block. Time is measured against theCLOCK_MONOTONIC clock. The call will block until either:

* a file descriptor delivers an event;

* the call is interrupted by a signal handler; or

* the timeout expires.

Note that the timeout interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the blocking interval may overrun by a small amount. Specifying a timeout of -1 causes epoll_wait() to block indefinitely, while specifying a timeout equal to zero cause epoll_wait() to return immediately, even if no events are available.

epoll_wait的maxevents该设置成多少呢?是不是如果有超过maxevents的事件就绪,就抛弃了?先看epoll_wait系统实现的调用栈。

epoll_wait
  ep_poll    
    ep_events_transfer    
        ep_collect_ready_items    
        ep_send_events

简单分析:
(1) ep_collect_ready_items 可以看出,事件之前是挂在一个列表ep->rdllist上的,这个函数就是把指定数量(该数量就是epoll_wait的参数maxevents)的事件挂到另一个列表txlist,也就是没有取出来的事件仍然挂在ep->rdllist上,不会丢失,下个epoll_wait再通知用户
(2) ep_send_events 执行的动作就是把列表txlist的内容放到缓冲区,然后复制到用户缓冲区maxevents 是epoll_wait可以处理的连接事件的最大限度值,这个值一般要小于或等于epoll_create的那个size,当然如果设置成比size还大 的话也无所谓,size是epoll整体可以监听的最大fd数量。maxevents的意义是防止epoll的API在填写你传进去的指针events的 时候,超过指针指向的内存的大小从而导致内存溢出。

results for ""

    No results matching ""