aboutsummaryrefslogtreecommitdiff
path: root/inotify.c
blob: 5ef0bf2b304b901084f42585bf144376eacf9892 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*This is the sample program to notify us for the file creation and file deletion takes place in “/tmp” directory*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <string.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

int main(void) {
  int length, i = 0;
  int fd;
  int wd;
  char buffer[EVENT_BUF_LEN];

  /*creating the INOTIFY instance*/
  fd = inotify_init();

  /*checking for error*/
  if ( fd < 0 ) {
    perror( "inotify_init" );
  }

  /*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/
  wd = inotify_add_watch( fd, "/home/ache/.tmp", IN_CREATE );

  /*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/
  while ( 1 ) {
      read( fd, buffer, EVENT_BUF_LEN ); 
      struct inotify_event *event = buffer + i;
      if ( event->len ) {
      if ( event->mask & IN_CREATE ) {
        if ( event->mask & IN_ISDIR ) {
          printf( "New directory %s created.\n", event->name );
        }
        else {
          printf( "New file %s created.\n", event->name );
          if( strcmp(event->name, "fox") == 0 ) {
              sleep(2);
              puts("🦊");
              break;
              char filename[512] = "/home/ache/.tmp";
              char filename_out[512] = "/tmp/";
              strcat(filename, event->name);
              strcat(filename_out, event->name);
              rename(filename, filename_out);
          }
        }
      }
    }
  }
  /*removing the “/tmp” directory from the watch list.*/
   inotify_rm_watch( fd, wd );

  /*closing the INOTIFY instance*/
   close( fd );

   return EXIT_SUCCESS;
}