是否可以(并且安全)使接受套接字不阻塞? [英] Is it possible (and safe) to make an accepting socket non-blocking?

查看:93
本文介绍了是否可以(并且安全)使接受套接字不阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来在阻塞上中断 accept() 调用插座.使用信号不是一种选择,因为这意味着要在库中,并且我不想使用户信号杂乱无章.使用select()是另一种选择,由于各种原因,buf在我看来不是很吸引人.

I'm looking for a way to interrupt an accept() call on a blocking socket. Using signals is not an option, as this is meant to be in a library and I don't want to clutter the user signals. Using select() is another option, buf for various reason it's not very appealing in my case.

如果可能的话,最好的方法是将套接字设置为非阻塞模式(使用 fcntl() O_NONBLOCK),而套接字在accept()调用中被阻止.预期的行为是accept()调用将在errno中以EAGAINEWOULDBLOCK返回.

What would work well, if possible, is to set the socket to non-blocking mode (using fcntl() and O_NONBLOCK) from another thread, while the socket is blocked on an accept() call. The expected behaviour is that the accept() call will return with EAGAIN or EWOULDBLOCK in errno.

确实可以那样工作吗?安全吗?便携的吗?

Would it indeed work like that? Is it safe? Portable?

如果您知道此方法对Windows的适用性(您需要在其中使用 FONBIO ),我也很感兴趣.

If you know about the applicability of this method to Windows (where you need to use WSAIoctl() and FONBIO), I'm also interested.

推荐答案

不了解Windows,但是POSIX保证了您想要的行为:

No idea about Windows, but the behavior you want is guaranteed by POSIX:

如果侦听队列中没有连接请求,并且未在套接字的文件描述符中设置O_NONBLOCK,则accept()将阻塞,直到存在连接为止.如果listen()队列中没有连接请求,并且套接字的文件描述符上设置了O_NONBLOCK,则accept()将失败,并将errno设置为[EAGAIN]或[EWOULDBLOCK].

If the listen queue is empty of connection requests and O_NONBLOCK is not set on the file descriptor for the socket, accept() shall block until a connection is present. If the listen() queue is empty of connection requests and O_NONBLOCK is set on the file descriptor for the socket, accept() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].

来源: http://pubs.opengroup.org/onlinepubs/9699919799/functions/accept.html

此外,selectpoll可用于通过轮询读取集中的侦听套接字来检查传入连接.

Also, select or poll can be used to check for incoming connections by polling for the listening socket in the reading set.

这篇关于是否可以(并且安全)使接受套接字不阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆