这是从“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);
}
select
可以用于 任何 文件类型描述符,无论是套接字、文件、管道或任何类似的描述符。但是,您不能使用它来监视文件何时被写入,为此您必须使用一些特定于操作系统的东西,例如在 Linux 上,您可以使用 inotify。 - Some programmer dude