Linux C 中的 poll 函数是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9167752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does the poll function work in c?
提问by user1161604
I am new to socket programming and I'm trying to figure out how poll works. So I made a little example program. The program seems to work as how I expect it to, but when I comment out the line that has int dummy
the for
loop only runs one iteration when it's suppose to do ten. What I don't understand is how that variable has anything to do with the for
loop. The program is suppose to print "timeout" after 3.5 secs and print "return hit" if there is input available.
我是套接字编程的新手,我试图弄清楚 poll 是如何工作的。所以我做了一个小例子程序。该方案似乎工作,因为我是如何想到,但是当我注释掉具有行int dummy
的for
循环只运行一次迭代时,它该做的十位。我不明白的是该变量与for
循环有何关系。该程序假设在 3.5 秒后打印“超时”并在有可用输入时打印“返回命中”。
#include <stdio.h>
#include <poll.h>
int main(int argc, char *argv[]) {
int a;
int b;
int c;
char buf[10];
int i;
struct pollfd ufds[1];
ufds[0].fd = 0;
ufds[0].events = POLLIN;
int rv;
int dummy;
for(i=0; i < 10; i++) {
printf("%i ", i);
if((rv = poll(ufds, 2, 3500)) == -1) perror("select");
else if (rv == 0) printf("Timeout occurred!\n");
else if (ufds[0].revents & POLLIN) {
printf("return hit\n");
read(0, buf, 10);
}
fflush(stdout);
}
return 0;
}
采纳答案by cnicutar
if((rv = poll(ufds, 2, 3500)) == -1) perror("select");
^
You are telling poll
you have 2 file descriptors (2 pollfd structures) but you only have one. That's undefined behavior(you're tricking poll to tread into unallocated memory). Change that argument to 1.
您告诉poll
您有 2 个文件描述符(2 个 pollfd 结构),但您只有一个。这是未定义的行为(你欺骗民意调查进入未分配的内存)。将该参数更改为 1。
回答by trojanfoe
The change in behaviour when commenting-out dummy
is likely because of changes to the stack that effect ufds
and the fact you are passing the wrong nfds
value into poll()
. You should also reset the values of pollfd.revents
before the next call to poll()
.
注释掉时行为dummy
的变化可能是因为堆栈发生了变化,ufds
以及您将错误的nfds
值传递到poll()
. 您还应该pollfd.revents
在下次调用 之前重置 的值poll()
。