linux下inotify机制代码示例

#include
#include
#include
#include
#include

#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUF_LEN (1024*(EVENT_SIZE+16))


void inotify_fun(struct inotify_event *event, void *puser)
{
    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 );
          }
     }
    if ( event->mask & IN_ACCESS )
    {
        if ( event->mask & IN_ISDIR )
        {
              printf( "The directory %s was access.\n", event->name );
        }
        else
        {
             printf( "The file %s was access.\n", event->name );
        }
    }

}

int fd;
int wd;

void main()
{

    fd = inotify_init1(0);
    if(fd == -1)
    {
    perror("inotify_init1");
    exit(0);
    }

    wd = inotify_add_watch(fd, "/dev/", IN_CREATE|IN_DELETE);
    if(wd == -1)
    {
    perror("inotify_add_watch");
    exit(0);
    }

    fd_set rfd;
    struct timeval tv;
    char bufevent[BUF_LEN] = {0};
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    for(;;)
    {
        int retval;
        FD_ZERO(&rfd);
        FD_SET(fd,&rfd);
        retval = select(fd+1, &rfd, NULL, NULL, &tv);
        if(retval == 0)
        {
              //printf("this is a cycle\n");
            continue;
        }
        else if(retval == -1)
        {
            return -1;
        }
        printf("this is a cycle\n");
        int len = read(fd, bufevent, BUF_LEN);
        int index = 0;
        while(index < len)
        {
            struct inotify_event *event = (struct inotify_event*)&bufevent[index];
            {
                inotify_fun(event,NULL);
                index += EVENT_SIZE +  event->len;
            }
        }
    }
}

你可能感兴趣的:(linux应用,linux内核之文件系统,linux)