Search code examples
c++cpolling

poll returns 0 but read does not block


I have been working on this piece of code for a while and for some reason poll returns zero even though there is data to be read in from the outFds pipe. For some reason if I read in some of the data and then run poll it returns the proper value, but this is not a solution. Has anybody seen this before and know what I should do?

#include <stdio.h>
#include <stdlib.h>
#include <sys/poll.h>

int main(void)
{
    int outFds[2];

    pipe(outFds);

    if(!fork()) {
        dup2(outFds[1], 1);

        close(outFds[0]);
        close(outFds[1]);

        // disable printf buffering
        setvbuf(stdout, NULL, _IONBF, 0);

        sleep(1);
        char buf[32];
        printf("blah");

        exit(0);
    }

    close(outFds[1]);

    char c;
    // Read 'b' into c. If this next line is not commented poll returns 1
    //read(outFds[0], &c, 1); 

    struct pollfd outFd;
    outFd.fd = outFds[0];
    outFd.events = POLLIN;
    printf("%d\n", poll(&outFd, 1, 0)); // poll returns 0 for some reason
}

Solution

  • From the manpage:

    Specifying a timeout of zero causes poll() to return immediately, even if no file descriptors are ready.

    I would read this as a timespec struct with tv_sec and tv_nsec set to 0, but it seems that putting a nullptr in has the same effect.