i want to watch a file fd is readable when not eof in linux c.
now i have to loop until !eof,i think it’s waste of cpu time.
static int rs_eof_read_binlog(rs_master_info_t *m, void *buf,
size_t size) {
FILE *fp;
size_t n;
fp = m->bfp;
for( ;; ) {
n = fread(buf, size, 1, fp);
if(n * size < size) {
if(ferror(fp) != 0) {
return RS_ERR;
}
if(feof(fp) != 0) {
fseek(fp, -n * size, SEEK_CUR);
sleep(1);
}
}
else {
break;
}
}
clearerr(fp);
return RS_OK;
}
i checkd the select,when a file eof ,select returns.
Those listed in readfds will be watched to see if characters become avail‐
able for reading (more precisely, to see if a read will not block; in particular, a file descriptor is also ready on end-of-file)
fixed!!!!
sample code use inotify
int main(int argc, char *argv[])
{
char p, buf[1024];
int fd = open("/home/terry/1.txt", O_RDONLY, "00666");
struct inotify_event * event;
size_t len;
read(fd, &p, 1);
int ifd = inotify_init();
int wd = inotify_add_watch(ifd, "/home/terry/1.txt", IN_MODIFY);
while(len = read(ifd, buf, 1024)) {
event = (struct inotify_event *) buf;
if(event->mask & IN_MODIFY) {
printf("changed\n");
break;
}
}
return 0;
}
You can try the
inotifymechanism.Use
inotify_add_watchto listen to theIN_MODIFYevent on the file you want to watch.