inotify 를 이용한 파일 시스템 감시

inotify 는 커널 2.6.13 이후 버전에서 사용가능하며 파일시스템의 접근, 변경, 삭제등의 동작을 알려주는 기능을 수행합니다.
모니터링 시스템에서 유용하게 사용가능하며 이벤트 감지의 통보를 파일시스템의 파일에 저장하며 바로 이벤트를 감지할 수 있으므로 다른 응용에도 사용 가능할 것으로 보입니다.

위키 백과 사전에도 설명되어 있듯이  3가지 api 를 지원합니다.

  • int inotify_init ()
  • int inotify_add_watch (int fd, const char* pathname, int mask)
  • nt inotify_rm_watch (int fd, int wd)

간단한 사용예는 다음과 같습니다.

#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 fd, wd;
  struct inotify_event *event;

  fd = inotify_init();
  wd = inotify_add_watch(fd, "/home/jklee3", IN_MODIFY | IN_CREATE | IN_DELETE );

  read( fd, buffer, BUF_LEN );

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

  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 );
  }

  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 );
  }

  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 );
  }

  inotify_rm_watch( fd, wd );
  close( fd );

  return 0;
}
Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.0 Korea License.
This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Notify me of followup comments via e-mail. You can also subscribe without commenting.