Created
March 25, 2018 06:30
-
-
Save illustris/6d6415af8e9d2f0be2abc2d662146f98 to your computer and use it in GitHub Desktop.
Example code for efficiently tailing a log file
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 <unistd.h> | |
#include <sys/types.h> | |
#include <sys/inotify.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#define EVENT_SIZE ( sizeof (struct inotify_event) ) | |
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) | |
typedef int FD ; | |
int main() { | |
char buffer[EVENT_BUF_LEN]; | |
FILE* filed = fopen("/dev/shm/typescript", "r" ); | |
setvbuf(filed, NULL, _IONBF, 0); | |
if( !filed ) { | |
printf("Openfile error\n"); | |
exit(-1); | |
} | |
char buf; | |
while(read(fileno(filed), &buf, 1) > 0) { | |
printf("%c",buf); | |
} | |
fflush(stdout); | |
int fd = inotify_init(); | |
if ( fd < 0 ) { | |
perror( "inotify_init error" ); | |
} | |
int wd = inotify_add_watch( fd, "/dev/shm/typescript", IN_CREATE | IN_DELETE | IN_ACCESS | IN_MODIFY | IN_OPEN ); | |
while(1) { | |
int length = read( fd, buffer, EVENT_BUF_LEN ); | |
//printf("==========\nUnblocked\n===========\n"); | |
if ( length < 0 ) { | |
perror( "read" ); | |
} | |
int i=0; | |
while ( i < length ) { | |
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ]; | |
if( event->len == 0) { | |
while(read(fileno(filed), &buf, 1) > 0) { | |
printf("%c",buf); | |
fflush(stdout); | |
} | |
} | |
i += EVENT_SIZE + event->len; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment