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;
}
原文地址:https://www.cnblogs.com/embedded-linux/p/8179803.html