select真的有限制嗎

在剛開始學習網絡編程時,似乎莫名其妙地就會被某人/某資料告訴select函數是有fd(file descriptor)數量限制的。在最近的一次記憶裏還有個人笑說select只支持64個fd。我甚至還寫過一篇不負責任甚至錯誤的博客(突破select的FD_SETSIZE限制)。有人說,直接重新定義FD_SETSIZE就可以突破這個select的限制,也有人說除了重定義這個宏之外還的重新編譯內核。

事實具體是怎樣的?實際上,造成這些混亂的原因恰好是不同平臺對select的實現不一樣。

Windows的實現

MSDN.aspx)上對select的說明:

int select(
  _In_     int nfds,
  _Inout_  fd_set *readfds,
  _Inout_  fd_set *writefds,
  _Inout_  fd_set *exceptfds,
  _In_     const struct timeval *timeout
);

nfds [in] Ignored. The nfds parameter is included only for compatibility with Berkeley sockets.

第一個參數MSDN只說沒有使用,其存在僅僅是爲了保持與Berkeley Socket的兼容。

The variable FD_SETSIZE determines the maximum number of descriptors in a set. (The default value of FD_SETSIZE is 64, which can be modified by defining FD_SETSIZE to another value before including Winsock2.h.) Internally, socket handles in an fd_set structure are not represented as bit flags as in Berkeley Unix.

Windows上select的實現不同於Berkeley Unix,後者使用位標誌來表示socket

在MSDN的評論中有人提到:

Unlike the Linux versions of these macros which use a single calculation to set/check the fd, the Winsock versions use a loop which goes through the entire set of fds each time you call FD_SET or FD_ISSET (check out winsock2.h and you’ll see). So you might want to consider an alternative if you have thousands of sockets!

不同於Linux下處理fd_set的那些宏(FD_CLR/FD_SET之類),Windows上這些宏的實現都使用了一個循環,看看這些宏的大致實現(Winsock2.h):

#define FD_SET(fd, set) do { \
    u_int __i; \
    for (__i = 0; __i < ((fd_set FAR *)(set))->fd_count; __i++) { \
        if (((fd_set FAR *)(set))->fd_array[__i] == (fd)) { \
            break; \
        } \
    } \
    if (__i == ((fd_set FAR *)(set))->fd_count) { \
        if (((fd_set FAR *)(set))->fd_count < FD_SETSIZE) { \
            ((fd_set FAR *)(set))->fd_array[__i] = (fd); \
            ((fd_set FAR *)(set))->fd_count++; \
        } \
    } \
} while(0)

看下Winsock2.h中關於fd_set的定義:

typedef struct fd_set {
    u_int fd_count;
    SOCKET fd_array[FD_SETSIZE];
} fd_set;

再看一篇更重要的MSDN Maximum Number of Sockets Supported.aspx):

The Microsoft Winsock provider limits the maximum number of sockets supported only by available memory on the local computer. The maximum number of sockets that a Windows Sockets application can use is not affected by the manifest constant FD_SETSIZE. If an application is designed to be capable of working with more than 64 sockets using the select and WSAPoll functions, the implementor should define the manifest FD_SETSIZE in every source file before including the Winsock2.h header file.

Windows上select支持的socket數量並不受宏FD_SETSIZE的影響,而僅僅受內存的影響。如果應用程序想使用超過FD_SETSIZE的socket,僅需要重新定義FD_SETSIZE即可。

實際上稍微想想就可以明白,既然fd_set裏面已經有一個socket的數量計數,那麼select的實現完全可以使用這個計數,而不是FD_SETSIZE這個宏。那麼結論是,select至少在Windows上並沒有socket支持數量的限制。當然效率問題這裏不談。

這看起來推翻了我們一直以來沒有深究的一個事實。

Linux的實現

在上面提到的MSDN中,其實已經提到了Windows與Berkeley Unix實現的不同。在select的API文檔中也看到了第一個參數並沒有說明其作用。看下Linux的man

nfds is the highest-numbered file descriptor in any of the three sets, plus 1.

第一個參數簡單來說就是最大描述符+1。

An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with a value of fd that is negative or is equal to or larger than FD_SETSIZE will result in undefined behavior.

明確說了,如果調用FD_SET之類的宏fd超過了FD_SETSIZE將導致undefined behavior。也有人專門做了測試:select system call limitation in Linux。也有現實遇到的問題:socket file descriptor (1063) is larger than FD_SETSIZE (1024), you probably need to rebuild Apache with a larger FD_SETSIZE

看起來在Linux上使用select確實有FD_SETSIZE的限制。有必要看下相關的實現 fd_set.h

typedef __uint32_t      __fd_mask;

/* 32 = 2 ^ 5 */
#define __NFDBITS       (32)
#define __NFDSHIFT      (5)
#define __NFDMASK       (__NFDBITS - 1)

/*
 * Select uses bit fields of file descriptors.  These macros manipulate
 * such bit fields.  Note: FD_SETSIZE may be defined by the user.
 */

#ifndef FD_SETSIZE
#define FD_SETSIZE      256
#endif

#define __NFD_SIZE      (((FD_SETSIZE) + (__NFDBITS - 1)) / __NFDBITS)

typedef struct fd_set {
    __fd_mask       fds_bits[__NFD_SIZE];
} fd_set;

在這份實現中不同於Windows實現,它使用了位來表示fd。看下FD_SET系列宏的大致實現:

#define FD_SET(n, p)    \
   ((p)->fds_bits[(unsigned)(n) >> __NFDSHIFT] |= (1 << ((n) & __NFDMASK)))

添加一個fd到fd_set中也不是Windows的遍歷,而是直接位運算。這裏也有人對另一份類似實現做了剖析:linux的I/O多路轉接select的fd_set數據結構和相應FD_宏的實現分析。在APUE中也提到fd_set

這種數據類型(fd_set)爲每一可能的描述符保持了一位。

既然fd_set中不包含其保存了多少個fd的計數,那麼select的實現裏要知道自己要處理多少個fd,那隻能使用FD_SETSIZE宏去做判定,但Linux的實現選用了更好的方式,即通過第一個參數讓應用層告訴select需要處理的最大fd(這裏不是數量)。那麼其實現大概爲:

for (int i = 0; i < nfds; ++i) {
    if (FD_ISSET...
       ...
}

如此看來,Linux的select實現則是受限於FD_SETSIZE的大小。這裏也看到,fd_set使用位數組來保存fd,那麼fd本身作爲一個int數,其值就不能超過FD_SETSIZE這不僅僅是數量的限制,還是其取值的限制。實際上,Linux上fd的取值是保證了小於FD_SETSIZE的(但不是不變的)Is the value of a Linux file descriptor always smaller than the open file limits?

Each process is further limited via the setrlimit(2) RLIMIT_NOFILE per-process limit on the number of open files. 1024 is a common RLIMIT_NOFILE limit. (It’s very easy to change this limit via /etc/security/limits.conf.)

fd的取值會小於RLIMIT_NOFILE,有很多方法可以改變這個值。這個值默認情況下和FD_SETSIZE應該是一樣的。這個信息告訴我們,Linux下fd的取值應該是從0開始遞增的(理論上,實際上還有stdin/stdout/stderr之類的fd)。這才能保證select的那些宏可以工作。

應用層使用

標準的select用法應該大致如下:

while (true) {
    ...
    select(...)
    for-each socket {
        if (FD_ISSET(fd, set))
            ...
    }

    ...
}

即遍歷目前管理的fd,通過FD_ISSET去判定當前fd是否有IO事件。因爲Windows的實現FD_ISSET都是一個循環,所以有了另一種不跨平臺的用法:

while (true) {
    ...
    select(. &read_sockets, &write_sockets..)
    for-each read_socket {
        use fd.fd_array[i)
    }
    ...
}

總結

  • Windows上select沒有fd數量的限制,但因爲使用了循環來檢查,所以效率相對較低
  • Linux上selectFD_SETSIZE的限制,但其相對效率較高
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章