Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Программирование под Unix/Linux > Отслеживание директория


Автор: opizius 22.5.2010, 12:19
нужно написать демон который отслеживал бы изменения(добавление новых файлов, удаление, изменение размера и времени модификации) в каком-то директории и выводил бы их (изменения!) в лог файл.

Интересует больше как именно отслеживать измененияsmile спс заранее.

Автор: djamshud 22.5.2010, 13:13
man 7 inotify

Автор: Warchief 29.5.2010, 17:00
вот пример inotify:

на bash'e:
Код

#!/bin/bash
MUSICDIR="/media/music"
function mpcUpdate() {
file=$* 
file=${file:$((${#MUSICDIR}+1))}
mpc update "$file" >/dev/null
}

echo "establishing watches for $MUSICDIR"
inotifywait -mr -e close_write -e move -e create -e delete --format "%w%f" $MUSICDIR | while read line
do
    mpcUpdate "$line"
done




а вот на cpp
Код

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


Автор: boostcoder 30.5.2010, 15:45
Warchief, раз уж копипастите чужой код, не плохо бы указать пруфлинк smile 
http://www.ibm.com/developerworks/ru/library/l-ubuntu-inotify/

при том, там еще и статья.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)