| 
                        
                         在实际开发中有时候会遇到许多文件的操作unix文件系统,或者需要对文件事件进行排查。当代码复杂度高到一定程度或者本身项目是使用多线程的时候(磁盘文件IO使用多线程本身并不是一种好的方案)。需要检测文件的事件来进行一些bug分析,这就需要用到文件IO事件的操作。 
一,使用系统API Inotify来监控文件事件 
在Linux系统中可以使用inotify系列函数来进行文件事件的监控。 
可以使用inotify函数来完成这项工作 
代码如下: 
#include 
#include 
#include 
#include 
#include 
#include 
#define EVENT_SIZE      (sizeof (struct inotify_event))
#define BUF_LEN         (10 * (EVENT_SIZE + 256))
static const char * filetype[] = "directory", "file";
static void
displayInotifyEvent(struct inotify_event * event)
    const char * type = (event->mask & IN_ISDIR) ? filetype[0] : filetype[1];
    if(event->len) 
        if(event->mask & IN_CREATE) 
            printf("The %s %s was created.\\n", type, event->name);
        
        else if(event->mask & IN_DELETE) 
            printf("The %s %s was deleted.\\n", type, event->name);
        
        else if(event->mask & IN_MODIFY) 
            printf("The %s %s was modified.\\n", type, event->name);
        
        
  
int main(int argc, char *argv[])
    int length, i = 0;
    int fd;
    int wd;
    char buffer[BUF_LEN] __attribute__((aligned(8)));
    
    const char * type;
    char *p;
    struct inotify_event *event;
    if(argc 
    
    for(;;) 
        length = read(fd, buffer, BUF_LEN);
        if(length < 0) 
            perror("read\\n");
            exit(EXIT_FAILURE);
        
        for(p = buffer; p < buffer + length;) 
            event = (struct inotify_event *) p;
            displayInotifyEvent(event);
            p += sizeof(struct inotify_event) + event->len;
        
    
    inotify_rm_watch(fd, wd);
    close(fd);
    exit(EXIT_SUCCESS);
 
使用方法: 
运行进程并监控home目录中的文件事件 
  
在另一个终端分辨进行各种文件操作:则在监控文件事件的进程会打印出各种文件事件的信息。 
  
TLPI中有一个完整的文件事件监控的例子,可以用于实际项目中debug 
二,使用HOOK来进行文件事件的监控。 
虽然inotify是基于内核来进行各种文件事件的监控,但是他所打印的事件仅针对执行成功的文件事件。如果文件操作过程中存在race-condition等问题导致文件损坏了,有时候使用内核事件并不能很好的定位代码中的问题。 
这时候可以使用hook来进行问题的定位。 
三、使用backtrace打印代码调用栈来排查问题代码。 
                                                (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |