Created
July 14, 2014 11:22
-
-
Save skrobul/c8cdcf02ec605a910943 to your computer and use it in GitHub Desktop.
file rewind check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <signal.h> | |
#include <linux/inotify.h> | |
#define EVENT_SIZE ( sizeof (struct inotify_event) ) | |
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) | |
#define WATCH_FLAGS IN_MODIFY | IN_MOVE_SELF | IN_DELETE_SELF | |
int fd, wd; | |
char buffer[EVENT_BUF_LEN]; | |
long prev = 0; | |
long totalEvents = 0; | |
int stopped = 0; | |
void check_size(wd) { | |
struct stat sb; | |
int i; | |
long len; | |
len = read(fd, buffer, EVENT_BUF_LEN); /* this is blocking, but its good */ | |
if (len < 0) { | |
perror("read"); | |
} | |
while(i < len) { | |
struct inotify_event * event = (struct inotify_event *) &buffer[i]; | |
/* file was modified */ | |
if( event->mask & IN_MODIFY) { | |
if (stat("/opt/syslog/archive.log", &sb) == -1) { | |
perror("stat"); | |
exit(-1); | |
} else { | |
long long curr_size = (long long) sb.st_size; | |
if(sb.st_size < prev) { | |
printf("\nFile rewound: current=%lld bytes, previous=%lld bytes\n", curr_size); | |
} | |
prev = curr_size; | |
}; | |
} | |
i += EVENT_SIZE + event->len; | |
totalEvents++; | |
printf("Processed %lld events.\r", totalEvents); | |
fflush(stdout); | |
} | |
i=0; | |
} | |
void cleanup() { | |
stopped = 1; | |
printf("Stopping...please wait...\n"); | |
/* nice citizen cleanup */ | |
inotify_rm_watch(fd, wd); | |
close(fd); | |
} | |
int main() { | |
printf("\n"); | |
/* setup signal catching */ | |
if (signal(SIGINT, cleanup) == SIG_ERR) exit(1); | |
if (signal(SIGTERM, cleanup) == SIG_ERR) exit(1); | |
/*creating the INOTIFY instance*/ | |
fd = inotify_init(); | |
/*checking for error*/ | |
if ( fd < 0 ) { | |
perror( "inotify_init failure" ); | |
} | |
wd = inotify_add_watch(fd, "/opt/syslog/archive.log", WATCH_FLAGS); | |
while(stopped != 1) { | |
check_size(wd); | |
} | |
cleanup(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment