检查套接字文件描述符是否可用? [英] Check Socket File Descriptor is Available?

查看:133
本文介绍了检查套接字文件描述符是否可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我得到一个文件描述符(套接字fd)如何检查fd是缴费读/写?
在我的情况下,客户端已连接到服务器,我们知道的FD。
但是,服务器将断开插座,是否有任何线索检查吗?

If I got a file descriptor (socket fd), how to check this fd is avaiable for read/write? In my situation, the client has connected to server and we know the fd. However, the server will disconnect the socket, are there any clues to check it ?

推荐答案

您想的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.

这篇关于检查套接字文件描述符是否可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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