基於redis ae實現 Linux中的檔案系統監控機制(inotify)

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   os   

(英文部分為轉的。代碼是個人代碼)

1 What’s inotify 
The inotify API provides a mechanism for monitoring file system events. Inotify can be used to monitor individual files, or to monitor directories. When a directory is monitored, inotify will return events for the directory itself, and for files inside the directory.  

2 How to use inotify

2.1 system calls used with this API
The following system calls are used with this API: inotify_init(orinotify_init1),inotify_add_watch, inotify_rm_watch, read, and close. 

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 is 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 that the kernel should monitor for the file referred to by that pathname. inotify_add_watch either creates a new watch item, or modifies an existing watch. Each watch has a unique "watch descriptor", an integer returned by inotify_add_watch when the watch is created. 2.1.3 inotify_rm_watchIt removes an item from an inotify watch list.When all file descriptors referring to an inotify instance have been closed, the underlying object and its resources are freed for reuse by the kernel; all associated watches are automatically freed. 2.1.4 readTo determine what events have occurred, an application reads from the inotify file descriptor. If no events have so far occurred, then, assuming a blocking file descriptor, read will block until at least one event occurs (unless interrupted by a signal, in which case the call fails with the error EINTR; see signal(7)). Each successful read returns 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 cookie;   /* Unique cookie associating related events (for rename ) */    uint32_t len;      /* Size of name field */    char     name[];   /* Optional null-terminated name */}; 2.2 Inotify eventsThe inotify_add_watch mask argument and the mask field of the inotify_event structure returned when reading an inotify file descriptor are both bit masks identifying inotify events. The following bits can be specified in mask when calling inotify_add_watch and may be returned in the mask field returned by read: IN_ACCESS                             File was accessed (read) (*).IN_ATTRIB                              Metadata changed, e.g., permissions, timestamps, extended attributes, link count (since Linux 2.6.25), UID, GID, etc. (*).IN_CLOSE_WRITE                  File opened for writing was closed (*).IN_CLOSE_NOWRITE            File not opened for writing was closed (*).IN_CREATE                             File/directory created in watched directory (*).IN_DELETE                             File/directory deleted from watched directory (*).IN_DELETE_SELF                   Watched file/directory was itself deleted.IN_MODIFY                            File was modified (*).IN_MOVE_SELF                      Watched file/directory was itself moved.IN_MOVED_FROM                 File moved out of watched directory (*).IN_MOVED_TO                       File moved into watched directory (*).IN_OPEN                                 File was opened (*).…… 2.3 The flow for the systme calls used with inotify 
3 程式碼範例
#include <sys/inotify.h>static aeEventLoop *loop;/* 全域的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);/* 建立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);/* 監控目錄下面的建立檔案事件 */ wd = inotify_add_watch(inotify_fd, dir, IN_CREATE); wds[wd] = dir; /* 監控目錄下面檔案的修改事件 */ wd = inotify_add_watch(inotify_fd, file, IN_MODIFY); wds[wd] = file; /* 監聽inotify的可讀事件, 有可讀事件, 則表示監控的檔案系統有事件產生 */ 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; ssize_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_CREATE) { /* new binlog files created */ if(event->len) { printf("New File created: %s\n", event->name); } } if(event->mask & IN_MODIFY) { /* existing files are modified */ printf("File is modified: %s\n", wds[event->wd]); } } }

這裡我只監控了建立和修改的兩個事件,然後根據檔案名稱字和一些其他的對應機制進行對檔案判斷修改等。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.