我看到了使用 accept4
的nginx源代码。当系统支持它时,它会使用accept4
。而我已经在谷歌上搜索到,Linux 2.6.28之后支持accept4
。
那么,accept4
和accept
之间有什么区别呢?
accept4
是一个非标准的 Linux 扩展。
真正的区别在于第四个参数 (flags
),它在 accept
中不存在:
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
int accept4(int sockfd, struct sockaddr *addr,socklen_t *addrlen, int flags);
来自:接受人手册
If flags is 0, then accept4() is the same as accept(). The following values can be bitwise ORed in flags to obtain different behavior:
SOCK_NONBLOCK Set the O_NONBLOCK file status flag on the new open file description. Using this flag saves extra calls to fcntl(2) to achieve the same result. SOCK_CLOEXEC Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the description of the O_CLOEXEC flag in open(2) for reasons why this may be useful.
并且来自:打开手册页面
默认情况下,新文件描述符设置为在execve(2)中保持打开状态(即,fcntl(2)中描述的FD_CLOEXEC文件描述符标志最初被禁用);下面描述的O_CLOEXEC标志可用于更改此默认值。
例如,通过使用此标志(SOCK_CLOEXEC
),可以避免多线程程序中的竞争条件,在其中可能会导致由fork(2)创建的子进程执行的程序意外泄漏open()返回的文件描述符到程序中。