poll--wait for some event on a file descriptor

Posted yuxi_o

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poll--wait for some event on a file descriptor相关的知识,希望对你有一定的参考价值。

poll同select,用于监控file descriptor事件,推荐用poll的升级版epool来实现功能,但在简单应用中使用poll更方便。

#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
struct pollfd {
  int fd;
  short events;
  short revents;
};

fds是文件描述符集的数组,nfds指定数组元素个数。

pollfd中fd是打开文件的文件描述符;events是输入参数,指定监控事件;revents是输出参数,被内核填充,只是实际发生的事件。

timeout指定超时毫秒数(milliseconds)。

成功返回正数,表示非0revents的fd个数,0表示超时,错误返回-1并设置errno。

On success, a positive number is returned; this is the number of structures which have  nonzero  revents  fields  
(in other words, those descriptors with events or errors reported).
A value of 0 indicates that the call timed out and no file descriptors were ready.
On error, -1 is returned, and errno is set appropriately.

应用举例

监控一个网络socket是否发生错误(刚链接时)。

int usock_wait_ready(int fd, int msecs) {
    struct pollfd fds[1];
    int res;

    fds[0].fd = fd; 
    fds[0].events = POLLOUT;

    res = poll(fds, 1, msecs);
    if (res < 0) {
        return errno;
    } else if (res == 0) {
        return -ETIMEDOUT;
    } else {
        int err = 0;
        socklen_t optlen = sizeof(err);

        res = getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &optlen);
        if (res)
            return errno;
        if (err)
            return err;
    }

    return 0;
}

 

以上是关于poll--wait for some event on a file descriptor的主要内容,如果未能解决你的问题,请参考以下文章

Linux内核笔记:epoll实现原理

linux 内核中epoll实现

System.Security.SecurityException The source was not found, but some or all event logs could not be

Why is HttpGet required only for some actions?

温习js中的for,forEach,map, some, every用法总结,跳出循环方法

温习js中的for,forEach,map, some, every用法总结,跳出循环方法