Basic concepts:
Inotify is a Linux feature that monitors file system operations such as read, write, and create. Inotify is sensitive, easy to use, and much more efficient than busy polling for cron tasks.
Demand:
1. There is a file collection process that needs to collect the log files. The log files may be deleted or moved.
2. We all know that once the file is deleted or moved, the process cannot continue to read the file data using the original open file fd.
3. Then you need to monitor the creation, movement, deletion and other states of the file to reopen it, so you need to use Inotify to do this.
Source code inotfy.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/inotify.h> #include <unistd.h> #define EVENT_NUM 12 char *event_str[EVENT_NUM] = { "IN_ACCESS", "IN_MODIFY", //File modification "IN_ATTRIB", "IN_CLOSE_WRITE", "IN_CLOSE_NOWRITE", "IN_OPEN", "IN_MOVED_FROM", //File move from "IN_MOVED_TO", //File move to "IN_CREATE", //File creation "IN_DELETE", //File deletion "IN_DELETE_SELF", "IN_MOVE_SELF" }; int main(int argc, char *argv[]) { int fd; int wd; int len; int nread; char buf[BUFSIZ]; struct inotify_event *event; int i; // Judge input parameters if (argc < 2) { fprintf(stderr, "%s path\n", argv[0]); return -1; } // Initialization fd = inotify_init(); if (fd < 0) { fprintf(stderr, "inotify_init failed\n"); return -1; } /* Add listening event * Listen for all events * Monitor whether the file is created, deleted or moved: in create, in delete, in moved, from in moved to */ wd = inotify_add_watch(fd, argv[1], IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO); if(wd < 0) { fprintf(stderr, "inotify_add_watch %s failed\n", argv[1]); return -1; } buf[sizeof(buf) - 1] = 0; while( (len = read(fd, buf, sizeof(buf) - 1)) > 0 ) { nread = 0; while(len> 0) { event = (struct inotify_event *)&buf[nread]; for(i=0; i<EVENT_NUM; i++) { if((event->mask >> i) & 1) { if(event->len > 0) fprintf(stdout, "%s --- %s\n", event->name, event_str[i]); else fprintf(stdout, "%s --- %s\n", " ", event_str[i]); } } nread = nread + sizeof(struct inotify_event) + event->len; len = len - sizeof(struct inotify_event) - event->len; } } return 0; }
Compile run:
gcc inotfy.c // Monitor file changes in the current directory ./a.out ./
Test results:
Summary:
1. The code can be adjusted and tested as required
2. reference: http://www.ibm.com/developerworks/cn/linux/l-inotify/
3. reference: http://www.jb51.net/article/37420.htm
- If the / etc/passwd file is modified, record the event in the file / root/modify_passwd.txt
- inotifywait -m /etc/passwd -e modify > /root/modify_passwd.txt
If the parameter - e is not added, the default is to monitor all events. During daily operation and maintenance, this tool can help you monitor the changes of important files and directories on the server.