【发布时间】:2012-08-07 18:26:56
【问题描述】:
这是来自“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只能在套接字上工作? -
问题已编辑。很抱歉造成混乱。
-
select可以用在 any 文件类型的描述符上,不管它是套接字、文件还是管道或任何类似的描述符。但是,您不能使用它来监视何时写入文件,因为您必须使用特定于操作系统的东西,例如在 Linux 上您可以使用 inotify。 -
我理解您评论的第一部分。但我认为选择套接字的目的基本上只是监听数据何时写入套接字。文件有什么不同?