码迷,mamicode.com
首页 > 其他好文 > 详细

记录一个inotify的侦听源码

时间:2015-05-27 19:28:00      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:include   记录   

#include <stdio.h>

#include <stdlib.h>

#include <errno.h>

#include <sys/types.h>

#include <sys/inotify.h>


#define EVENT_SIZE  ( sizeof (struct inotify_event) )

#define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )


int main( int argc, char **argv ) 

{

  int length, i = 0;

  int fd;

  int wd;

  char buffer[BUF_LEN];


  fd = inotify_init();


  if ( fd < 0 ) {

    perror( "inotify_init" );

  }


  wd = inotify_add_watch( fd, "/home/strike", 

                         IN_MODIFY | IN_CREATE | IN_DELETE );

  length = read( fd, buffer, BUF_LEN );  


  if ( length < 0 ) {

    perror( "read" );

  }  


  while ( i < length ) {

    struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];

    if ( event->len ) {

      if ( event->mask & IN_CREATE ) {

        if ( event->mask & IN_ISDIR ) {

          printf( "The directory %s was created.\n", event->name );       

        }

        else {

          printf( "The file %s was created.\n", event->name );

        }

      }

      else if ( event->mask & IN_DELETE ) {

        if ( event->mask & IN_ISDIR ) {

          printf( "The directory %s was deleted.\n", event->name );       

        }

        else {

          printf( "The file %s was deleted.\n", event->name );

        }

      }

      else if ( event->mask & IN_MODIFY ) {

        if ( event->mask & IN_ISDIR ) {

          printf( "The directory %s was modified.\n", event->name );

        }

        else {

          printf( "The file %s was modified.\n", event->name );

        }

      }

    }

    i += EVENT_SIZE + event->len;

  }


  ( void ) inotify_rm_watch( fd, wd );

  ( void ) close( fd );


  exit( 0 );

}



本文出自 “tring” 博客,请务必保留此出处http://warcraft3.blog.51cto.com/6514883/1655660

记录一个inotify的侦听源码

标签:include   记录   

原文地址:http://warcraft3.blog.51cto.com/6514883/1655660

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!