LoginSignup
13
12

More than 5 years have passed since last update.

inotifyを使ってみた。

Last updated at Posted at 2013-03-07

inotifyというディレクトリやファイルを監視する仕組みがあるらしい。そこで使ってみた。下記は、引数でファイルを与え、そのファイルへの変更を監視するサンプルです。
inotify_init()でfdを取得して、inotify_add_watch()で監視するイベント、ファイル(ディレクトリ)を設定し、read()を使って、発生したイベントを取得する仕組みです。
tail -fとかもこんな感じで処理している気がします。

inotify_sample.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#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 ) )

void inotify_events_loop( int fd );
int inotify_read_events( int fd );

int main( int argc, char **argv ) 
{
    int fd = -1;
    int wd = -1;
    char *filename = NULL;

    if  ( argc != 2 ) {
        fprintf( stderr, "Usage:%s filepath\n", argv[0]);
        goto ERROR;
    } 

    filename = argv[1];

    if( (fd = inotify_init()) == -1 ) {
        perror( "inotify_init" );
        goto ERROR;
    }

    wd = inotify_add_watch( fd, argv[1], 
            IN_MODIFY | IN_CREATE | IN_DELETE );

    inotify_events_loop( fd );

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

    return 0;
ERROR:
    return 1;
}

void inotify_events_loop( int fd )
{
    int count = -1;
    while(1) {
        count = inotify_read_events( fd );
        fprintf( stdout, "events count[%d]\n", count);
    }
}

int inotify_read_events( int fd )
{
    int count = 0;
    int i = 0;
    char buffer[BUF_LEN];
    int length = 0;
    if( (length = read( fd, buffer, BUF_LEN ) ) < 0 ) return count;

    while ( i < length ) {
        struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
        /* 必要なイベントの処理 */
        if ( event->mask & IN_MODIFY ) {
            printf("%s file is modify\n",  event->name);
        }
        i += EVENT_SIZE + event->len;
        count++;
    }
    return count;
}
13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12