-1

I write a program by inotify to check file change in loop for grab any changes to that. but i think this can be done better. can anybody write this code better?

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>
#include <sys/select.h>
#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )
int event_check (int fd)
{
  fd_set rfds;
  FD_ZERO (&rfds);
  FD_SET (fd, &rfds);
  /* Wait until an event happens or we get interrupted 
     by a signal that we catch */
  return select (FD_SETSIZE, &rfds, NULL, NULL, NULL);
  }

int main( )
{
  int length, i = 0;
  int fd;
  int wd;
while(1){
i=0;
  fd = inotify_init();

  if ( fd < 0 ) {
    perror( "inotify_init" );
  }

  wd = inotify_add_watch( fd, "/tmp/test", IN_CLOSE_WRITE);
    if (event_check (fd) > 0)
    {
        char buffer[EVENT_BUF_LEN];
        int count = 0;
        length = read( fd, buffer, EVENT_BUF_LEN ); 
        if ( length < 0 ) {
            perror( "read" );
          } 
         while ( i < length ) {     struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ]; 
            printf( "New file %s Editted.\n", event->name );
            i += EVENT_SIZE + event->len;
          }
    }
}
    inotify_rm_watch( fd, wd );
   close( fd );
}
Majid
  • 13,853
  • 15
  • 77
  • 113
hamSh
  • 1,163
  • 1
  • 13
  • 27

2 Answers2

1

I think you only need one inotify_init for one program and only one inotify_add_watch for one directory. Can you please paste the "init and add_watch outside the loop" version which you said doesn't work?

yuyichao
  • 768
  • 6
  • 28
0

I've never used inotify, so its possible that this might be wrong but here's a couple of changes that I think might "improve" your code.

  1. I don't think there's any reason to put either inotify_init or inotify_add_watch inside the loop. Just do this initialisation work once, before the loop.

  2. I'm not sure why you've created the event_check function. You aren't specifying a timeout and you're only using a single file descriptor, so I think read will give you the same funcionality.

torak
  • 5,684
  • 21
  • 25