• inotify监测实例


     1 /*************************************************************************
     2     > File Name: inotify.c
     3     > 监测一个目录下的文件变化,增加或删除提示
     4     > Created Time: Thu 21 Sep 2017 02:41:48 PM CST
     5  ************************************************************************/
     6 
     7 #include <stdio.h>
     8 #include <sys/inotify.h>
     9 #include <string.h>
    10 #include <errno.h>
    11 #include <fcntl.h>
    12 
    13 int read_process_inotify_fd(int inotify_fd)
    14 {
    15     int res;
    16     char event_buf[512];
    17     int event_size;
    18     int event_pos = 0;
    19     struct inotify_event *event;
    20     res = read(inotify_fd, event_buf, sizeof(event_buf));
    21     if(res < sizeof(struct inotify_event))
    22     {
    23         if(errno == EINTR)
    24         {
    25             return 0;
    26         }
    27         printf("can not get event ,%s
    ",strerror(errno));
    28         return -1;
    29     }
    30 
    31     while(res >= (int)sizeof(*event)) {
    32         event = (struct inotify_event *)(event_buf + event_pos); //指向下一个结构体
    33         if(event->len) {
    34             if(event->mask & IN_CREATE) {
    35                 printf("Add device '%s' due to inotify event
    ", event->name);
    36             } else {
    37                 printf("Removing device '%s' due to inotify event
    ", event->name);
    38             }
    39         }
    40         event_size = sizeof(*event) + event->len;
    41         res -= event_size;
    42         event_pos += event_size; //跳转到下一个结构体 
    43     }
    44     return 0;
    45 }
    46 
    47 int main(int argc ,char **argv)
    48 {
    49     int fd;
    50     if(argc < 2)
    51     {
    52         printf("Usage: %s <dir>
    ",argv[0]);
    53         return -1;
    54     }
    55     // inotify_init
    56     fd = inotify_init();
    57     // add watch
    58     //添加监控:argv[1]监控目录,IN_DELETE|IN_CREATE 监控 创建和删除
    59     inotify_add_watch(fd, argv[1], IN_DELETE|IN_CREATE); 
    60     // read
    61     while(1)
    62     {
    63         read_process_inotify_fd(fd);
    64     }
    65     return 0;
    66 }
    View Code

  • 相关阅读:
    vue 自定义组件销毁
    通过微信公众号API复制公众号自定义菜单同时增加子菜单方法
    shell 常用案例
    java 与 CDH kafka集成
    CDH 安装 kafka
    linux下Vim文本编辑器的常用快捷键
    shell 启动和停止脚本
    CHD 5.15 安装 Kylin
    hive on spark
    kafka-mirror不稳定问题分析与解决方法
  • 原文地址:https://www.cnblogs.com/winfu/p/7569170.html
Copyright © 2020-2023  润新知