select 和 epoll的編程實現區別

最近有朋友在面試的時候被問了select 和epoll效率差的緣由,和通常人同樣,大部分都會回答select是輪詢、epoll是觸發式的,因此效率高。這個答案聽上去很完美,大體也說出了兩者的主要區別。
今天閒來無事,翻看了下內核代碼,結合內核代碼和你們分享下個人觀點。

1、鏈接數
我本人也曾經在項目中用過select和epoll,對於select,感觸最深的是linux下select最大數目限制(windows 下彷佛沒有限制),每一個進程的select最多能處理FD_SETSIZE個FD(文件句柄),
若是要處理超過1024個句柄,只能採用多進程了。
常見的使用slect的多進程模型是這樣的: 一個進程專門accept,成功後將fd經過unix socket傳遞給子進程處理,父進程能夠根據子進程負載分派。曾經用過1個父進程+4個子進程 承載了超過4000個的負載。
這種模型在咱們當時的業務運行的很是好。epoll在鏈接數方面沒有限制,固然可能須要用戶調用API重現設置進程的資源限制。

2、IO差異
一、select的實現

這段能夠結合linux內核代碼描述了,我使用的是2.6.28,其餘2.6的代碼應該差很少吧。
先看看select:
select系統調用的代碼在fs/Select.c下,

  1. asmlinkage long sys_select(int n, fd_set __user *inp, fd_set __user *outp,
  2.             fd_set __user *exp, struct timeval __user *tvp)
  3. {
  4.     struct timespec end_time, *to = NULL;
  5.     struct timeval tv;
  6.     int ret;

  7.     if (tvp) {
  8.         if (copy_from_user(&tv, tvp, sizeof(tv)))
  9.             return -EFAULT;

  10.         to = &end_time;
  11.         if (poll_select_set_timeout(to,
  12.                 tv.tv_sec + (tv.tv_usec / USEC_PER_SEC),
  13.                 (tv.tv_usec % USEC_PER_SEC) * NSEC_PER_USEC))
  14.             return -EINVAL;
  15.     }

  16.     ret = core_sys_select(n, inp, outp, exp, to);
  17.     ret = poll_select_copy_remaining(&end_time, tvp, 1, ret);

  18.     return ret;
  19. }

前面是從用戶控件拷貝各個fd_set到內核空間,接下來的具體工做在core_sys_select中,

  1. core_sys_select->do_select,真正的核心內容在do_select裏:
  2. int do_select(int n, fd_set_bits *fds, struct timespec *end_time)
  3. {
  4.     ktime_t expire, *to = NULL;
  5.     struct poll_wqueues table;
  6.     poll_table *wait;
  7.     int retval, i, timed_out = 0;
  8.     unsigned long slack = 0;

  9.     rcu_read_lock();
  10.     retval = max_select_fd(n, fds);
  11.     rcu_read_unlock();

  12.     if (retval < 0)
  13.         return retval;
  14.     n = retval;

  15.     poll_initwait(&table);
  16.     wait = &table.pt;
  17.     if (end_time && !end_time->tv_sec && !end_time->tv_nsec) {
  18.         wait = NULL;
  19.         timed_out = 1;
  20.     }

  21.     if (end_time && !timed_out)
  22.         slack = estimate_accuracy(end_time);

  23.     retval = 0;
  24.     for (;;) {
  25.         unsigned long *rinp, *routp, *rexp, *inp, *outp, *exp;

  26.         set_current_state(TASK_INTERRUPTIBLE);

  27.         inp = fds->in; outp = fds->out; exp = fds->ex;
  28.         rinp = fds->res_in; routp = fds->res_out; rexp = fds->res_ex;

  29.         for (i = 0; i < n; ++rinp, ++routp, ++rexp) {
  30.             unsigned long in, out, ex, all_bits, bit = 1, mask, j;
  31.             unsigned long res_in = 0, res_out = 0, res_ex = 0;
  32.             const struct file_operations *f_op = NULL;
  33.             struct file *file = NULL;

  34.             in = *inp++; out = *outp++; ex = *exp++;
  35.             all_bits = in | out | ex;
  36.             if (all_bits == 0) {
  37.                 i += __NFDBITS;
  38.                 continue;
  39.             }

  40.             for (j = 0; j < __NFDBITS; ++j, ++i, bit <<= 1) {
  41.                 int fput_needed;
  42.                 if (i >= n)
  43.                     break;
  44.                 if (!(bit & all_bits))
  45.                     continue;
  46.                 file = fget_light(i, &fput_needed);
  47.                 if (file) {
  48.                     f_op = file->f_op;
  49.                     mask = DEFAULT_POLLMASK;
  50.                     if (f_op && f_op->poll)
  51.                         mask = (*f_op->poll)(file, retval ? NULL : wait);
  52.                     fput_light(file, fput_needed);
  53.                     if ((mask & POLLIN_SET) && (in & bit)) {
  54.                         res_in |= bit;
  55.                         retval++;
  56.                     }
  57.                     if ((mask & POLLOUT_SET) && (out & bit)) {
  58.                         res_out |= bit;
  59.                         retval++;
  60.                     }
  61.                     if ((mask & POLLEX_SET) && (ex & bit)) {
  62.                         res_ex |= bit;
  63.                         retval++;
  64.                     }
  65.                 }
  66.             }
  67.             if (res_in)
  68.                 *rinp = res_in;
  69.             if (res_out)
  70.                 *routp = res_out;
  71.             if (res_ex)
  72.                 *rexp = res_ex;
  73.             cond_resched();
  74.         }
  75.         wait = NULL;
  76.         if (retval || timed_out || signal_pending(current))
  77.             break;
  78.         if (table.error) {
  79.             retval = table.error;
  80.             break;
  81.         }

  82.         /*
  83.          * If this is the first loop and we have a timeout
  84.          * given, then we convert to ktime_t and set the to
  85.          * pointer to the expiry value.
  86.          */
  87.         if (end_time && !to) {
  88.             expire = timespec_to_ktime(*end_time);
  89.             to = &expire;
  90.         }

  91.         if (!schedule_hrtimeout_range(to, slack, HRTIMER_MODE_ABS))
  92.             timed_out = 1;
  93.     }
  94.     __set_current_state(TASK_RUNNING);

  95.     poll_freewait(&table);

  96.     return retval;
  97. }

上面的代碼不少,其實真正關鍵的代碼是這一句:

  1. mask = (*f_op->poll)(file, retval ? NULL : wait);

這個是調用文件系統的 poll函數,不一樣的文件系統poll函數天然不一樣,因爲咱們這裏關注的是tcp鏈接,而socketfs的註冊在 net/Socket.c裏。
register_filesystem(&sock_fs_type); 
socket文件系統的函數也是在net/Socket.c裏:

  1. static const struct file_operations socket_file_ops = {
  2.     .owner = THIS_MODULE,
  3.     .llseek = no_llseek,
  4.     .aio_read = sock_aio_read,
  5.     .aio_write = sock_aio_write,
  6.     .poll = sock_poll,
  7.     .unlocked_ioctl = sock_ioctl,
  8. #ifdef CONFIG_COMPAT
  9.     .compat_ioctl = compat_sock_ioctl,
  10. #endif
  11.     .mmap = sock_mmap,
  12.     .open = sock_no_open, /* special open code to disallow open via /proc */
  13.     .release = sock_close,
  14.     .fasync = sock_fasync,
  15.     .sendpage = sock_sendpage,
  16.     .splice_write = generic_splice_sendpage,
  17.     .splice_read = sock_splice_read,
  18. };

從sock_poll跟隨下去,
最後能夠到 net/ipv4/tcp.c的
unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait) 
這個是最終的查詢函數,
也就是說select 的核心功能是調用tcp文件系統的poll函數,不停的查詢,若是沒有想要的數據,主動執行一次調度(防止一直佔用cpu),直到有一個鏈接有想要的消息爲止。
從這裏能夠看出select的執行方式基本就是不一樣的調用poll,直到有須要的消息爲止,若是select 處理的socket不少,這其實對整個機器的性能也是一個消耗。

二、epoll的實現

epoll的實現代碼在 fs/EventPoll.c下,
因爲epoll涉及到幾個系統調用,這裏不逐個分析了,僅僅分析幾個關鍵點,
第一個關鍵點在
static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
             struct file *tfile, int fd) 
這是在咱們調用sys_epoll_ctl 添加一個被管理socket的時候調用的函數,關鍵的幾行以下:
epq.epi = epi;
    init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);

    /*
     * Attach the item to the poll hooks and get current event bits.
     * We can safely use the file* here because its usage count has
     * been increased by the caller of this function. Note that after
     * this operation completes, the poll callback can start hitting
     * the new item.
     */
    revents = tfile->f_op->poll(tfile, &epq.pt); 
這裏也是調用文件系統的poll函數,不過此次初始化了一個結構,這個結構會帶有一個poll函數的callback函數:ep_ptable_queue_proc,
在調用poll函數的時候,會執行這個callback,這個callback的功能就是將當前進程添加到 socket的等待進程上。

  1. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  2.                  poll_table *pt)
  3. {
  4.     struct epitem *epi = ep_item_from_epqueue(pt);
  5.     struct eppoll_entry *pwq;

  6.     if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
  7.         init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
  8.         pwq->whead = whead;
  9.         pwq->base = epi;
  10.         add_wait_queue(whead, &pwq->wait);
  11.         list_add_tail(&pwq->llink, &epi->pwqlist);
  12.         epi->nwait++;
  13.     } else {
  14.         /* We have to signal that an error occurred */
  15.         epi->nwait = -1;
  16.     }
  17. }

注意到參數 whead 其實是 sk->sleep,其實就是將當前進程添加到sk的等待隊列裏,當該socket收到數據或者其餘事件觸發時,會調用
sock_def_readable 或者sock_def_write_space 通知函數來喚醒等待進程,這2個函數都是在socket建立的時候填充在sk結構裏的。
從前面的分析來看,epoll確實是比select聰明的多、輕鬆的多,不用再苦哈哈的去輪詢了。
相關文章
相關標籤/搜索