这是来自“man select”的代码示例加上几行来读取正在写入的实际文件。我怀疑当写入./myfile.txt
时,select
将返回它现在可以从该fd读取。但是,只要txt文件存在,select就会在while循环中不断返回。我希望它只在新数据写入文件末尾时返回。我认为这应该是如何运作的。
#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);
}
答案 0 :(得分:15)