Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the poll function work in c?

Tags:

c

linux

sockets

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;
}
like image 636
user1161604 Avatar asked Feb 06 '12 21:02

user1161604


People also ask

What is poll () use for?

The poll() function is used to enable an application to multiplex I/O over a set of descriptors. For each member of the array pointed to by fds, poll() will examine the given descriptor for the event(s) specified. nfds is the number of pollfd structures in the fds array.

What is the difference between select and poll in polling method?

select() only uses (at maximum) three bits of data per file descriptor, while poll() typically uses 64 bits per file descriptor. In each syscall invoke poll() thus needs to copy a lot more over to kernel space.

How does Linux poll work?

When poll() is called for some file descriptor, the corresponding device poll_xyx() method registered with file operation structure is invoked in kernel space. This method then checks if the data is readily available, if this condition is true then the event mask is set and the poll returns to user space.

What is poll in socket?

The poll() function identifies those socket descriptors on which an application can read or write data, or on which an error event has occurred. Parameter Description listptr. A pointer to an array of pollfd structures. Each structure specifies a socket descriptor and the events of interest for this socket.


1 Answers

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.

like image 122
cnicutar Avatar answered Oct 05 '22 21:10

cnicutar