系统相关
首页 > 系统相关> > poll C Linux函数如何工作?

poll C Linux函数如何工作?

作者:互联网

我正在阅读C编程中的民意调查,并在poll(2)手册页中构建了一个应用程序.
这是一个例子:

#include<stdio.h>
#include <stropts.h>
#include <poll.h>
#include <fcntl.h>

int main() {

    struct pollfd fds[2];
    int timeout_msecs = -1;
    int ret;
    int i;

    /* Open STREAMS device. */
    fds[0].fd = open("/home/jeshwanth/mywork/poll/dev0", O_RDONLY);
    fds[1].fd = open("/home/jeshwanth/mywork/poll/dev1", O_RDONLY);
    fds[0].events = POLLOUT | POLLWRBAND;
    fds[1].events = POLLOUT | POLLWRBAND;

    while (1) {
        ret = poll(fds, 2, timeout_msecs);

        if (ret > 0) {
            /* An event on one of the fds has occurred. */
            for (i = 0; i < 2; i++) {
                if (fds[i].revents != 0) {
                    /* Priority data may be written on device number i. */
                    printf(
                            "Priority Data may be written on device number %d POLLWRBAND\n",
                            i);

                }
                if (fds[i].revents = !0) {
                    /* Data may be written on device number i. */
                    printf("Data may be written on device number %d POLLOUT\n",
                            i);
                }
                if (fds[i].revents = !0) {
                    /* A hangup has occurred on device number i. */
                    printf("A hangup has occurred on device number %d\n", i);

                }
            }
        }
    }
    return 0;
}

注意:dev0和dev1是普通文件.当我运行程序时,如果dev0和dev1中没有发生任何事件,则显示该消息.但我期待一些写入文件发生时,只有它应该显示消息.我错了吗?

解决方法:

轮询输出就绪并不意味着当出现输出时会收到通知:这意味着当有输出缓冲区空间可以输出时会收到通知(但是你仍然应该检查输出函数的返回值) ,缓冲状态可能在轮询和输出之间发生了变化;总是检查返回值).

标签:c-3,linux,polling
来源: https://codeday.me/bug/20190620/1247892.html