Skip to content

Instantly share code, notes, and snippets.

@illustris illustris/example.c
Created Mar 25, 2018

Embed
What would you like to do?
Example code for efficiently tailing a log file
#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
You can’t perform that action at this time.