looyao
2015-12-05 18:25:15 +08:00
这里可以粘帖代码么,额
//tail_demo.c
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
int tail(char *path, long *pos);
int main(int argc, char *argv[])
{
int inotify_fd, watch_fd, n;
long pos;
struct inotify_event event;
void *evp;
char *path;
if (argc != 2) {
return -1;
}
path = argv[1];
pos = 0;
if (tail(path, &pos) < 0) {
return -2;
}
evp = &event;
inotify_fd = inotify_init();
watch_fd = inotify_add_watch(inotify_fd, path, IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF);
if (watch_fd <= 0) {
fprintf(stderr, "inotify_add_watch error:%s\n", path);
return -3;
}
//这里可以使用 select, poll 轮询下 inotify_fd
while (1) {
bzero(&event, sizeof(struct inotify_event));
n = read(inotify_fd, evp, sizeof(struct inotify_event));
if (n <= 0) {
fprintf(stderr, "read error\n");
break;
}
if (event.mask & IN_MODIFY) {
tail(path, &pos);
}
}
}
int tail(char *path, long *pos)
{
FILE *handle;
char buf[1024];
handle = fopen(path, "r");
if (!handle) {
fprintf(stderr, "can't open file:%s\n", path);
return -1;
}
fseek(handle, *pos, SEEK_SET);
while (!feof(handle)) {
bzero(buf, sizeof(buf));
fgets(buf, sizeof(buf), handle);
printf("%s", buf);
*pos = ftell(handle);
}
fclose(handle);
}
编译:
gcc tail_demo.c -o tail_demo
使用:
./tail_demo 文件路径