加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Linux阻塞式pollfd使用

(2020-05-01 11:30:13)
标签:

linux

pollfd

select

分类: programming
先看一个openvswitch中的例子:
==================================
int check_connection_completion(int fd)
{
    static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
    struct pollfd pfd;
    int retval;

    pfd.fd = fd;
    pfd.events = POLLOUT;

#ifndef _WIN32
    do {
        retval = poll(&pfd, 1, 0);
    } while (retval < 0 && errno == EINTR);
#else
    fd_set wrset, exset;
    FD_ZERO(&wrset);
    FD_ZERO(&exset);
    FD_SET(fd, &exset);
    FD_SET(fd, &wrset);
    pfd.revents = 0;
    struct timeval tv = { 0, 0 };
   
    retval = select(0, NULL, &wrset, &exset, &tv);
    if (retval == 1) {
        if (FD_ISSET(fd, &wrset)) {
            pfd.revents |= pfd.events;
        }
        if (FD_ISSET(fd, &exset)) {
            pfd.revents |= POLLERR;
        }
    }
#endif
    if (retval == 1) {
        if (pfd.revents & (POLLERR | POLLHUP)) {
            ssize_t n = send(fd, "", 1, 0);
            if (n < 0) {
                return sock_errno();
            } else {
                VLOG_ERR_RL(&rl, "poll return POLLERR but send succeeded");
                return EPROTO;
            }
        }
        return 0;
    } else if (retval < 0) {
        VLOG_ERR_RL(&rl, "poll: %s", sock_strerror(sock_errno()));
        return errno;
    } else {
        return EAGAIN;
    }
}
==========================================
poll调用和select调用实现的功能一样,都是网络IO利用的一种机制,等待文件描述符集中的一个事件发生来执行IO操作,函数原型。
===============================

#include 

       

int poll(struct pollfd *
fds, nfds_t nfds, int timeout);

#define _GNU_SOURCE
#include
#include

int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *tmo_p, const sigset_t *sigmask);
=================================

struct pollfd定义如下:
==============================
struct pollfd {
   int fd;
   short events;
   short revents;
};
===========================
系统定义了这些事件:

POLLIN   --  有数据可读
POLLPRI  -- 读事件
POLLOUT  -- 写事件允许
POLLRDHUP --流socket对端关闭连接
POLLERR   -- 错误
POLLHUP   -- 挂起事件

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有