usando inotify para monitorar o acesso a um arquivo

2

Eu gostaria de ter um gatilho e quando um determinado arquivo é acessado por algum processo, eu gostaria de ser notificado (por exemplo, um script deve ser executado). Se bem entendi, isso poderia ser alcançado com inotify .

Se eu tiver um arquivo /foo/bar.txt , como configuro inotify para monitorar esse arquivo?

Estou usando o Debian Wheezy com o kernel 3.12 (meu kernel tem suporte a inotify)

    
por Martin Vegter 05.06.2014 / 12:45

2 respostas

3

De acordo com Gilles em Super Usuário :

Simple, using inotifywait (install your distribution's inotify-tools package):

while inotifywait -e close_write myfile.py; do ./myfile.py; done

This has a big limitation: if some program replaces myfile.py with a different file, rather than writing to the existing myfile, inotifywait will die. Most editors work that way.

To overcome this limitation, use inotifywait on the directory:

while true; do
  change=$(inotifywait -e close_write,moved_to,create .)
  change=${change#./ * }
  if [ "$change" = "myfile.py" ]; then ./myfile.py; fi
done
    
por 05.06.2014 / 13:05
2

A interface básica do shell para inotify é inotifywait de inotify-tools .

Para monitorar todos os acessos a um arquivo:

inotifywait -mq --format '%e' /path/to/file |
while IFS= read -r events; do
  /path/to/script "$events"
done

Seu script é chamado com uma lista separada por vírgula de eventos simultâneos, sempre que algo acontece com o arquivo (ler, escrever, fechar,…).

    
por 06.06.2014 / 04:14

Tags