How to choose () to wait on regular file descriptors (non-sockets)?

This is sample code from "man select" plus a few lines to read the actual file that is being written to. I suspected that when ./myfile.txt is written, select will return that it can now read from this fd. But what happens is that select constantly returns in the while loop while the txt file exists. I want it to be returned only when new data is written to the end of the file. I thought that it should be so.

 #include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> int main(void) { fd_set rfds; struct timeval tv; int retval; int fd_file = open("/home/myfile.txt", O_RDONLY); /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(0, &rfds); FD_SET(fd_file, &rfds); /* Wait up to five seconds. */ tv.tv_sec = 5; tv.tv_usec = 0; while (1) { retval = select(fd_file+1, &rfds, NULL, NULL, &tv); /* Don't rely on the value of tv now! */ if (retval == -1) perror("select()"); else if (retval) printf("Data is available now.\n"); /* FD_ISSET(0, &rfds) will be true. */ else printf("No data within five seconds.\n"); } exit(EXIT_SUCCESS); } 
+8
c select file-io
source share
1 answer

Disk files are always ready for reading (but reading can return 0 bytes if you are already at the end of the file), so you cannot use select() in the disk file to find out when new data is added to the file.

POSIX says:

File descriptors associated with regular files should always be set to true for readability, readiness for writing, and error conditions.

In addition, as cnicutar indicated in the remote entry, in general, you need to initialize FD_SET at each iteration. In your code, you are tracking one fd, and fd is always ready, so FD_SET doesn't actually change. However, if you have 5 descriptors for monitoring, and select detects that only one is ready, then at the next iteration only one descriptor will be monitored (unless you reset FD_SET). This makes using select difficult.

+13
source share

All Articles