如何在C投票功能工作? [英] How does the poll function work in c?
问题描述
我是新来的Socket编程,我试图找出如何调查工作。所以我做了一个小例子程序。该方案似乎我怎么指望它工作,但是当我注释掉该行有 INT假
在为
循环,只有当它的假设做10次运行一次迭代。我不明白的是,可变如何有什么用为
循环。该方案是假设后3.5秒和打印,打印超时,打回,如果有输入可用。
的#include<&stdio.h中GT;
#包括LT&;&poll.h GT;INT主(INT ARGC,CHAR *的argv []){
int类型的;
INT B:
INT℃;
焦炭BUF [10];
INT I;
结构的pollfd个UFD [1];
个UFD [0] .FD = 0;
UFD上[0] = .events POLLIN;
INT RV;
INT假;
对于(I = 0; I&小于10;我++){
的printf(%i的,我);
如果((RV =轮询(UFD上,2,3500))== -1)PERROR(选择);
否则,如果(RV == 0)printf的(超时发生\\ n!);
否则如果(个UFD [0] .revents&放大器; POLLIN){
的printf(返回命中\\ n);
读(0,BUF,10);
}
fflush(标准输出);
}
返回0;
}
IF((RV =轮询(UFD上,2,3500))== -1)PERROR(选择 );
^
您告诉调查
你有2个文件描述符(2 pollfd结构),但你只能有一个。这就是未定义行为(你欺骗民意调查踏入未分配的内存)。这样的说法改为1。
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.
#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;
}
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.
这篇关于如何在C投票功能工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!