inotify使用

NAME
inotify - monitoring filesystem events


DESCRIPTION
The  inotify  API  provides  a mechanism for monitoring filesystem 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.


 The following system calls are used with this API:


*  inotify_init(2) creates an inotify instance and returns a file descriptor referring to the inotify instance.
*  inotify_add_watch(2) 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(2) 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(2) when the watch is created.


*  When events occur for monitored files and directories, those events are made available to the application as 
structured data that can be read from the inotify file descriptor using read(2).


*  inotify_rm_watch(2) removes an item from an inotify watch list.


*  When all file descriptors referring to an inotify instance have been closed (using close(2)), 
       the underlying object and its resources are freed for reuse  by  the  kernel;  all  associated watches are automatically freed.


       With  careful  programming,  an  application can use inotify to efficiently monitor and cache the state of a set of filesystem objects.  
       However, robust applications should allow for the fact that bugs in the monitoring logic or races of the kind described below may 
       leave the cache inconsistent with the filesystem state.  It is probably wise to do some  consistency  checking,  and
       rebuild the cache when inconsistencies are detected.


Reading events from an inotify file descriptor
       To  determine  what events have occurred, an application read(2)s from the inotify file descriptor.  
       If no events have so far occurred, then, assuming a blocking file descriptor, read(2) 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(2) returns a buffer containing one or more of the following structures:


           struct inotify_event {
               int      wd;       /* Watch descriptor */
               uint32_t mask;     /* Mask describing event */
               uint32_t cookie;   /* Unique cookie associating related
                                     events (for rename(2)) */
               uint32_t len;      /* Size of name field */
               char     name[];   /* Optional null-terminated name */
           };


       wd identifies the watch for which this event occurs.  It is one of the watch descriptors returned by a previous call to inotify_add_watch(2).


       mask contains bits that describe the event that occurred (see below).


       cookie is a unique integer that connects related events.  Currently this is used only for rename events, and allows the resulting pair of 
       IN_MOVED_FROM and IN_MOVED_TO events to be  connected by the application.  For all other event types, cookie is set to 0.


       The  name field is present only when an event is returned for a file inside a watched directory; it identifies the filename within to the watched directory.  
       This filename is null-terminated, and may include further null bytes ('\0') to align subsequent reads to a suitable address boundary.


       The len field counts all of the bytes in name, including the null bytes; the length of each inotify_event structure is thus sizeof(struct inotify_event)+len.


   inotify events
       The  inotify_add_watch(2)  mask  argument  and the mask field of the inotify_event structure returned when read(2)ing an inotify file descriptor are both bit masks identifying inotify events.
       The following bits can be specified in mask when calling inotify_add_watch(2) and may be returned in the mask field returned by read(2):


           IN_ACCESS (+)
                  File was accessed (e.g., read(2), execve(2)).


           IN_CREATE (+)
                  File/directory created in watched directory (e.g., open(2) O_CREAT, mkdir(2), link(2), symlink(2), bind(2) on a UNIX domain socket).


/********demo:******/
           fd = inotify_init1(IN_NONBLOCK);
           /* Allocate memory for watch descriptors */
           wd = calloc(argc, sizeof(int));
           /* Mark directories for events
              - file was opened
              - file was closed */
           for (i = 1; i < argc; i++) {
               wd[i] = inotify_add_watch(fd, argv[i],IN_OPEN | IN_CLOSE);
           }


           /* Prepare for polling */
           nfds = 2;
           /* Console input */


           fds[0].fd = STDIN_FILENO;
           fds[0].events = POLLIN;


           /* Inotify input */
           fds[1].fd = fd;
           fds[1].events = POLLIN;


           /* Wait for events and/or terminal input */


           while (1) {
               poll_num = poll(fds, nfds, -1);


               if (poll_num > 0) {
                   if (fds[1].revents & POLLIN) {
                       /* Inotify events are available */
                       handle_events(fd, wd, argc, argv);
                   }
               }
           }


       static void
       handle_events(int fd, int *wd, int argc, char* argv[])
       {
           /* Some systems cannot read integer variables if they are not
              properly aligned. On other systems, incorrect alignment may
              decrease performance. Hence, the buffer used for reading from
              the inotify file descriptor should have the same alignment as
              struct inotify_event. */


           char buf[4096]
               __attribute__ ((aligned(__alignof__(struct inotify_event))));
           const struct inotify_event *event;
           int i;
           ssize_t len;
           char *ptr;


           /* Loop while events can be read from inotify file descriptor. */
           for (;;) {
               /* Read some events. */


               len = read(fd, buf, sizeof buf);
               /* If the nonblocking read() found no events to read, then
                  it returns -1 with errno set to EAGAIN. In that case,
                  we exit the loop. */


               if (len <= 0)
                   break;


               /* Loop over all events in the buffer */


               for (ptr = buf; ptr < buf + len;
                       ptr += sizeof(struct inotify_event) + event->len) {


                   event = (const struct inotify_event *) ptr;


                   /* Print event type */
                   if (event->mask & IN_OPEN)
                       printf("IN_OPEN: ");
                   if (event->mask & IN_CLOSE_NOWRITE)
                       printf("IN_CLOSE_NOWRITE: ");
                   if (event->mask & IN_CLOSE_WRITE)
                       printf("IN_CLOSE_WRITE: ");


                   /* Print the name of the watched directory */
                   for (i = 1; i < argc; ++i) {
                       if (wd[i] == event->wd) {
                           printf("%s/", argv[i]);
                           break;
                       }
                   }
                   /* Print the name of the file */


                   if (event->len)
                       printf("%s", event->name);


                   /* Print type of filesystem object */


                   if (event->mask & IN_ISDIR)
                       printf(" [directory]\n");
                   else
                       printf(" [file]\n");
               }
           }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值