Disk files are always ready to read (but the read might return 0 bytes if you're already at the end of the file), so you can't use select()
on a disk file to find out when new data is added to the file.
POSIX says:
File descriptors associated with regular files shall always select true for ready to read, ready to write, and error conditions.
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); }
所以,只要文件/home/myfile.txt存在,程序都将在while(1)中不停的输出:Data is available now.
Data is available now.
Data is available now.
Data is available now.
……