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.
我是socket编程的新手,我正在试图弄清楚poll是如何工作的。所以我做了一个小例子程序。该程序看起来像我期望的那样工作,但是当我注释掉具有int dummy的行时,for循环只运行一次迭代,当它假设为10时。我不明白的是该变量与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;
}
2 个解决方案
#1
7
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.
你告诉民意调查你有2个文件描述符(2个pollfd结构),但你只有一个。这是未定义的行为(你正在欺骗民意调查以进入未分配的内存)。将该参数更改为1。
#2
2
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()
.
注释掉虚拟时行为的变化可能是因为影响ufds的堆栈更改以及将错误的nfds值传递给poll()的事实。您还应该在下次调用poll()之前重置pollfd.revents的值。
#1
7
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.
你告诉民意调查你有2个文件描述符(2个pollfd结构),但你只有一个。这是未定义的行为(你正在欺骗民意调查以进入未分配的内存)。将该参数更改为1。
#2
2
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()
.
注释掉虚拟时行为的变化可能是因为影响ufds的堆栈更改以及将错误的nfds值传递给poll()的事实。您还应该在下次调用poll()之前重置pollfd.revents的值。