我是套接字编程的新手,我试图弄清楚民意调查是如何运作的。所以我做了一个小例子程序。该程序看起来像我期望的那样工作,但是当我注释掉int dummy
for
循环时,for
循环只运行一次迭代,当它假设为10时。我不明白的是该变量与#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;
}
循环有什么关系。该程序假设打印&#34;超时&#34; 3.5秒后打印&#34;返回&#34;如果有可用的输入。
{{1}}
答案 0 :(得分:7)
if((rv = poll(ufds, 2, 3500)) == -1) perror("select");
^
你告诉poll
你有2个文件描述符(2个pollfd结构),但你只有一个。这是未定义的行为(您正在欺骗民意调查以进入未分配的内存)。将该参数更改为1。
答案 1 :(得分:2)
注释掉dummy
时的行为更改可能是因为影响ufds
的堆栈更改以及您将错误的nfds
值传递给poll()
的事实}。您还应在下次调用pollfd.revents
之前重置poll()
的值。