Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. /*This is the sample program to notify us for the file creation and file deletion takes place in “/tmp” directory*/
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #include <sys/types.h>
  6. #include <linux/inotify.h>
  7.  
  8. #define EVENT_SIZE ( sizeof (struct inotify_event) )
  9. #define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
  10.  
  11. int main( )
  12. {
  13. int length, i = 0;
  14. int fd;
  15. int wd;
  16. char buffer[EVENT_BUF_LEN];
  17.  
  18. /*creating the INOTIFY instance*/
  19. fd = inotify_init();
  20.  
  21. /*checking for error*/
  22. if ( fd < 0 ) {
  23. perror( "inotify_init" );
  24. }
  25.  
  26. /*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/
  27. wd = inotify_add_watch( fd, "/tmp", IN_CREATE | IN_DELETE );
  28.  
  29. /*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/
  30.  
  31. length = read( fd, buffer, EVENT_BUF_LEN );
  32.  
  33. /*checking for error*/
  34. if ( length < 0 ) {
  35. perror( "read" );
  36. }
  37.  
  38. /*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/
  39. while ( i < length ) { struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ]; if ( event->len ) {
  40. if ( event->mask & IN_MODIFY ) {
  41.  
  42. printf( "New directory %s MODIFY.\n", event->name );
  43.  
  44. else {
  45. printf( "N222\n", event->name );
  46. }
  47. }
  48. else if ( event->mask & IN_DELETE ) {
  49. if ( event->mask & IN_ISDIR ) {
  50. printf( "Directory %s deleted.\n", event->name );
  51. }
  52. else {
  53. printf( "File %s deleted.\n", event->name );
  54. }
  55. }
  56. }
  57. i += EVENT_SIZE + event->len;
  58. }
  59. /*removing the “/tmp” directory from the watch list.*/
  60. inotify_rm_watch( fd, wd );
  61.  
  62. /*closing the INOTIFY instance*/
  63. close( fd );
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement