且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查套接字文件描述符是否可用?

更新时间:2023-11-28 12:51:28

您想的fcntl()来检查的FD读/写设置:

You want fcntl() to check for read/write settings on the fd:

#include <unistd.h>
#include <fcntl.h>

int    r;

r = fcntl(fd, F_GETFL);
if (r == -1)
        /* Error */
if (r & O_RDONLY)
    /* Read Only */
else if (r & O_WRONLY)
    /* Write Only */
else if (r & O_RDWR)
    /* Read/Write */

但是,这是从当套接字不再连接一个单独的问题。如果你已经在使用选择()调查()那么你几乎没有。 调查()如果您指定将返回状态很好 POLLERR 事件的revents 检查它>。

But this is a separate issue from when the socket is no longer connected. If you are already using select() or poll() then you're almost there. poll() will return status nicely if you specify POLLERR in events and check for it in revents.

如果你正在做正常阻塞I / O然后只处理读/因为他们进来写入错误和正常恢复。

If you're doing normal blocking I/O then just handle the read/write errors as they come in and recover gracefully.