#include <unistd.h>#include<sys/inotify.h>#include<stdio.h>#include<error.h>#include<errno.h>#include<string.h>#defineError (Text) error (1, errno, "%s", text)typedefstructtest{intFlag; Const Char*name;} Eventmask;intFreadsome (void*dest, size_t remain, FILE *file) { Char*offset = (Char*) dest; while(remain) {intn = fread (offset,1, remain, file); if(n==0) { return-1; } remain-=N; Offset+=N; } return 0;}intMainintargcChar*argv[]) { Const Char*Target; if(ARGC = =1) {target="."; } Else{target= argv[1]; } eventmask event_masks[]={{in_access,"in_access"}, {in_attrib,"In_attrib"}, {in_close_write,"In_close_write"}, {in_close_nowrite,"In_close_nowrite"}, {in_create,"in_create"}, {in_delete,"In_delete"}, {in_delete_self,"in_delete_self"}, {in_modify,"in_modify"}, {in_move_self,"in_move_self"}, {in_moved_from,"In_moved_from"}, {in_moved_to,"in_moved_to"}, {in_open,"In_open"}, {in_dont_follow,"In_dont_follow"}, {in_excl_unlink,"In_excl_unlink"}, {in_mask_add,"In_mask_add"}, {in_oneshot,"In_oneshot"}, {in_onlydir,"In_onlydir"}, {in_ignored,"in_ignored"}, {in_isdir,"In_isdir"}, {in_q_overflow,"In_q_overflow"}, {in_unmount,"In_unmount"} , }; intMonitor =Inotify_init (); if( -1==monitor) {ERROR ("Monitor"); } intWatcher =Inotify_add_watch (monitor, Target, in_all_events); if( -1==watcher) {ERROR ("Inotify_add_watch"); } FILE*monitor_file = Fdopen (monitor,"R"); Charlast_name[1024x768]; Charname[1024x768]; /*event:inotify_event-Name:char[event.len]*/ while(1) { structInotify_eventEvent; if( -1= = Freadsome (&Event,sizeof(Event) (Monitor_file)) {ERROR ("Freadsome"); } if(Event. Len) {freadsome (name,Event. Len, Monitor_file); } Else{sprintf (name,"FD:%d\n",Event. WD); } if(strcmp (name, last_name)! =0) {puts (name); strcpy (last_name, name); } /*show the meaning of mask for event*/ inti =0; for(i=0; i<sizeof(event_masks)/sizeof(Eventmask); ++i) {if(Event. Mask &Event_masks[i].flag) {printf ("\t%s\n", Event_masks[i].name); } } } return 0;}
Using INotify to detect file changes in a Linux directory