Implementation of file system monitoring mechanism in Linux based on Redis AE (inotify)

Source: Internet
Author: User
Tags inotify

(The English part is a turn.) Code is personal code)

1 What ' s inotify  
The < Span style= "Line-height:1.6em" >inotify  api provides a mechanism for monitoring file system events. Inotify can used to monitor individual files, or to monitor directories. When a directory is monitored, inotify'll return events for the directory itself, and for files inside the DIRECTORY.&NB SP;  

2 How to use INotify

2.1 system calls used with the This API
The following system calls is used with this API: inotify_init(orinotify_init1 ), inotify_add_watch ,  inotify_rm_watch ,   read < Span style= "Line-height:1.6em" >close . &NBSP;

2.1.1 Inotify_init
It creates an INotify instance and returns a file descriptor referring to the INotify instance. The more recent inotify_init1 are like inotify_init, but provides some extra functionality.

2.1.2 Inotify_add_watchIt manipulates the "watch list" associated with an inotify instance. Each item ("Watch") in the watch list specifies the pathname of a file or directory, along with some set of events th E kernel should monitor for the file referred through to the pathname.Inotify_add_watcheither creates a new watch item, or modifies an existing watch. Each watch have a unique "watch descriptor", an integer returned byInotify_add_watchWhen the watch is created.2.1.3 inotify_rm_watch It removes a item from an inotify watch list.When any file descriptors referring to an inotify instance has been closed, the underlying object and its resources a Re freed for reuse by the kernel; All associated watches is automatically freed.2.1.4 Readto determine what events has occurred, an applicationReads from the inotify file descriptor. If No events has so far occurred, then, assuming a blocking file descriptor,Readwould block until at least one event occurs (unless interrupted by a signal, in which case the call fails with the Err or eintr; SeeSignal(7)).Each successful readreturns a buffer containing one or more of the following structures:struct Inotify_event {int wd; /* Watch Descriptor * /uint32_t Mask; /* Mask of events * /uint32_t cookies; /* Unique cookie Associating related events ( forRename ) */uint32_t Len; /* Size of name field * /Char name[]; /* Optional null-terminated name * /}; 2.2 Inotify Events theInotify_add_watchmask argument and the Mask field of the inotify_event structure returned whenReading an inotify file descriptor is both bit masks identifying inotify events. The following bits can specified in mask when callingInotify_add_watchreturned in the Mask field returned byRead:in_accessFile was accessed (read) (*).In_attribMetadata changed, e.g, permissions, timestamps, extended attributes, link count (since Linux 2.6.25), UID, GID, etc. (*).In_close_writeFile opened for writing is closed (*).In_close_nowriteFile not opened for writing is closed (*).in_createfile/directory created in watched directory (*).In_deletefile/directory deleted from watched directory (*).in_delete_selfwatched File/directory was itself deleted.in_modifyFile was modified (*).in_move_selfwatched File/directory was itself moved.In_moved_fromFile moved out of watched directory (*).in_moved_toFile moved into watched directory (*).In_openFile was opened (*)....2.3 The flow for the SYSTME calls used with INotify
3 Code Examples
#include <sys/inotify.h>static aeeventloop *loop;/* Global Notify Watch Item */static const char *WDS[10]; void Sync_file_thread (Void*args) {int inotify_fd, wd; int poll_num; const char *dir, *file; dir = "/data/wcl/redis_proxy" ; File = "Binlog_1"; Loop =aecreateeventloop (1024);/* Create inotify instance */inotify_fd = inotify_init1 (In_nonblock); if (inotify_fd = =-1) {perror ("Unable to create inotify instance\n"); exit ( -1);} printf ("Inotify_fd [%d]\n", INOTIFY_FD); /* New file event under the Monitoring directory */WD = Inotify_add_watch (inotify_fd, dir, in_create); WDS[WD] = dir; /* Monitor directory for modification events under Files */WD = Inotify_add_watch (inotify_fd, file, in_modify); WDS[WD] = file; /* Listen for inotify readable events, there is a readable event, which indicates that the monitored file system has event generation */if (Aecreatefileevent (loop,inotify_fd,ae_readable,handle_inotify_events , NULL)) {exit (0);}  Aemain (loop); Aedeleteeventloop (loop);} void handle_inotify_events (struct aeeventloop *eventloop, int fd, void *clientdata, int mask) {char buf[4096], *ptr; ssiz e_t Len;  struct Inotify_event *event; Len = Read (FD, BUF, sizeof (BUF)); if (len = =-1 && errno! = eagain) {perror ("read error"); exit ( -1);} if (len <= 0) {return;} for (ptr = buf; PTR < buf + len; PTR + = sizeof (struct inotify_event) + Event->len) {event = (struct inotify_event *) ptr; if (Event->mask & In_cre ATE) {/* new Binlog files created */if (Event->len) {printf ("New File Created:%s\n", Event->name);}} if (event-& Gt;mask & in_modify) {/* Existing files are modified */printf ("File is modified:%s\n", WDS[EVENT-&GT;WD]);}} }

Here I only monitor the creation and modification of the two events, and then according to the name of the file and some other corresponding mechanism to determine the file changes and so on.

Related Article

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.