2

I creates two files in the execution folder of the following code, one named test and the other is test2. I run the following code in one terminal which "monitors" those two files for changes, but the select call returns all the time even when the file is not touched.

#include <fcntl.h>      /* fcntl */
#include <sys/select.h> /* select */
#include <stdio.h> /* NULL */

int main() {

    fd_set readfds, writefds;
    int max_fd;

    int fd_1 = open("test", O_RDWR  | O_NONBLOCK);
    int fd_2 = open("test2", O_RDWR | O_NONBLOCK);

    if(fd_1 == -1)
        return -1;

    if(fd_2 == -1)
        return -1;


    while(1) {

        FD_ZERO(&readfds);
        FD_ZERO(&writefds);

        FD_SET(fd_1, &readfds);
        FD_SET(fd_2, &readfds);
        FD_SET(fd_1, &writefds);
        FD_SET(fd_2, &writefds);

        max_fd = (fd_2 > fd_1 ? fd_2 : fd_1) + 1;

        int t_rdy = select(max_fd, &readfds, &writefds, NULL, NULL);

        if(t_rdy == -1)
            return -1;

        int t_fd;
        for(t_fd = 0; t_fd < max_fd; t_fd++) {

            if(t_fd <= 2) continue;

            printf("READ  LIST %d: %s \n", t_fd, (FD_ISSET(t_fd, &readfds) ? "set" : "nope"));
            printf("WRITE LIST %d: %s \n", t_fd, (FD_ISSET(t_fd, &writefds) ? "set" : "nope"));
        }

    }

    return 0;
}
ArmenB
  • 2,125
  • 3
  • 23
  • 47
  • shouldn't you do `sleep` in this cycle too? also, perhaps just `continue` instead of `return` if you don't get a value that makes sense. – Ashalynd Sep 10 '14 at 23:48
  • if return of select is -1, that is an error why continue. Regardless that might not be relevant in this case. – ArmenB Sep 10 '14 at 23:51

1 Answers1

2

This is exactly the behavior I would expect. As far as select() is concerned, disk files are always ready to be read from or written to.

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96