You can use the inotify mechanism provided by Linux 2.6 kenel to monitor file system changes, such as adding, deleting, and modifying files.
The following is an example program that can be used to monitor a directory. If you create, delete, or modify a file under this directory, a prompt will be displayed to print the information to the screen.
# Include <sys/inotify. h>
# Include <stdio. h>
# Include <errno. h>
# Include <sys/types. h>
# Include <unistd. h>
# Include <sys/ioctl. h>
# Define BUF_LEN 4096.
Int main (int argc, char ** argv)
...{
If (argc <2 )...{
Printf ("Usage: % s [directory]", argv [0]);
Return-1;
}
Int fd;
Fd = inotify_init ();
If (fd =-1 )...{
Printf ("failed in inotify_init, % d", errno );
Return-1;
}
Int wd1, wd2;
ADD_AGAIN:
Wd1 = inotify_add_watch (fd, argv [1], IN_DELETE | IN_MODIFY | IN_CREATE | IN_IGNORED );
If (wd1 =-1 )...{
Perror ("inotify_add_watch ");
Return-1;
} Else
Printf ("new watch fd % d", wd1 );
/**//*
WD2 = inotify_add_watch (FD, "/etc", in_access | in_modify );
If (WD2 =-1 ){
Perror ("inotify_add_watch ");
Return-1;
}
*/
Char Buf [buf_len] _ attribute _ (aligned (4 )));
Ssize_t Len, I = 0;
Unsigned int queue_len;
Int ret;
While (1 )...{
I = 0;
Ret = IOCTL (FD, fionread, & queue_len );
If (ret <0 )...{
Perror ("ioctl ");
}
Len = read (fd, buf, BUF_LEN );
While (I <len )...{
Struct inotify_event * event = (struct inotify_event *) & buf [I];
Printf ("wd = % d mask = % d cookie = % d len = % d dir = % s ",
Event-> wd, event-> mask, event-> cookie, event-> len, (event-> mask & IN_ISDIR )? "Yes": "no ");
If (event-> len)
Printf ("name = % s", event-> name );
If (event-> mask & IN_IGNORED )...{
Printf ("ignored, add again ");
If (0! = Inotify_rm_watch (fd, event-> wd ))
Perror ("inotify_rm_watch ");
Goto ADD_AGAIN;
}
I + = sizeof (struct inotify_event) + event-> len;
}
}
Return 0;
}