1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| #include <sys/select.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
/**
* Compilation : gcc inotify-exemple.c -o inotify-exemple -O2 -Wall -W -Werror -ansi -pedantic
**/
int fd, wd;
void sigint_handler(int signum)
{
(void) signum;
/* Nous ne surveillons plus ce fichier/répertoire */
if (inotify_rm_watch(fd, wd)) {
perror("inotify_rm_watch");
exit(EXIT_FAILURE);
}
/* Fermeture du descripteur de fichier obtenu lors de l'initialisation d'inotify */
if (close(fd) < 0) {
perror("close");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
void afficher_masque(int mask)
{
printf("Evénement : ");
if (mask & IN_ACCESS)
printf("Accès");
if (mask & IN_MODIFY)
printf("Modification");
if (mask & IN_ATTRIB)
printf("Attributs");
if (mask & IN_CLOSE)
printf("Fermeture");
if (mask & IN_OPEN)
printf("Ouverture");
if (mask & IN_MOVED_FROM)
printf("Déplacé de");
if (mask & IN_MOVED_TO)
printf("Déplacé vers");
if (mask & IN_MOVE_SELF)
printf("Lui-même déplacé");
if (mask & IN_DELETE)
printf("Suppression");
if (mask & IN_CREATE)
printf("Création");
if (mask & IN_DELETE_SELF)
printf("Lui-même supprimé");
if (mask & IN_UNMOUNT)
printf("N'est pas monté");
if (mask & IN_Q_OVERFLOW)
printf("Queue saturée");
if (mask & IN_IGNORED)
printf("Ignoré");
if (mask & IN_ISDIR)
printf("(répertoire)");
else
printf("(fichier)");
}
int main(int argc, char *argv[])
{
size_t r;
fd_set fds;
char buffer[8192];
struct inotify_event *event;
if (argc != 2) {
fprintf(stderr, "usage : %s fichier_ou_répertoire_à_monitorer\n", argv[0]);
return EXIT_FAILURE;
}
/* Initialisation d'inotify */
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return EXIT_FAILURE;
}
/* Surveillance du fichier/répertoire passé en paramètre
* On accepte tous les évènements possibles */
wd = inotify_add_watch(fd, argv[1], IN_ALL_EVENTS);
if (wd < 0) {
perror("inotify_add_watch");
return EXIT_FAILURE;
}
printf("Monitoring : '%s' (numéro = %d)\n", argv[1], wd);
/* Capture de SIGINT (Ctrl + C) */
signal(SIGINT, sigint_handler);
while (1) {
FD_ZERO(&fds);
FD_SET(fd, &fds);
if (select(fd + 1, &fds, NULL, NULL, 0) <= 0) {
continue;
}
/* Obtention des informations sur l'évènement qui vient de se produire */
r = read(fd, buffer, sizeof(buffer));
if (r <= 0) {
perror("read");
return EXIT_FAILURE;
}
event = (struct inotify_event *) buffer;
printf("Fichier surveillé n°%d\t", event->wd);
afficher_masque(event->mask);
if (event->len) {
printf("\tObjet : %s", event->name);
}
printf("\n");
}
return EXIT_FAILURE;
} |
Partager