套接字accept()是否返回描述符阻塞或非阻塞?

时间:2011-11-08 15:58:27

标签: c sockets

accept()函数在阻塞或非阻塞模式下返回套接字描述符吗?

4 个答案:

答案 0 :(得分:5)

来自man 2 accept

   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.

因此,我希望从accept()返回的套接字描述符处于阻塞模式。

答案 1 :(得分:4)

不,套接字不会从侦听套接字继承非阻塞状态。你必须自己做非阻塞。

答案 2 :(得分:0)

Windows会将non-block属性转移到返回的套接字中

Linux不会,您必须将套接字显式设置为非阻塞(最简单的方法是使用非阻塞标志调用accept4)

答案 3 :(得分:0)

来自accept(2)

<块引用>

在Linux上,accept()返回的新socket不继承file 来自侦听套接字的状态标志,例如 O_NONBLOCK 和 O_ASYNC。 此行为不同于规范的 BSD 套接字实现。 可移植程序不应依赖于继承或非继承 文件状态标志,并始终显式设置所有必需的标志 从 accept() 返回的套接字。

所以,Linux 似乎是个奇葩。 BSD 和 Windows 似乎确实继承了非阻塞行为。