Use inotify to monitor File System Changes

Source: Internet
Author: User
Tags inotify

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;
}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.