linux system programming, 283p
리눅스에 파일, 디렉토리를 감시하는 watch가 있다. 특정 경로를 설정하여 감시하여 적절한 이벤트를 작성할 수 있다.
#include <sys/inotify.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#define BUF_LEN 128
//int inotify_init1 (int flags);
void main(){
int fd; //file descritor
int wd; //watch descriptor
const char path[50]="/home/now0930/test/ttt";
fd = inotify_init1 (0);
if (fd == -1) {
perror("inotify_init1");
exit(EXIT_FAILURE);
}
//printf("%d", IN_MODIFY);
wd = inotify_add_watch(fd, path, IN_OPEN);
if (wd == -1){
perror("add notify");
exit(EXIT_FAILURE);
}
printf("file descriptor is %d\n",fd);
printf("path is %s\n",path);
//__attribute__ compiler가 제공하는 메모리 번지 정렬. 4바이트 단위로 정렬.
//https://blog.naver.com/PostView.nhn?blogId=msyang59&logNo=220885276415
char buf[BUF_LEN] __attribute__((aligned(4)));
//printf("buf[0] is 0x%ld\n",&buf[0]);
//printf("buf[1] is 0x%ld\n",&buf[1]);
//printf("buf[2] is 0x%ld\n",&buf[2]);
//printf("buf[3] is 0x%ld\n",&buf[3]);
//printf("buf[4] is 0x%ld\n",&buf[4]);
//printf("buf[5] is 0x%ld\n",&buf[5]);
//
//
ssize_t len, i = 0;
for (int j=0;j<5;j++){
i = 0;
/* read BUF_LEN bytes' worth of events */
len = read (fd, buf, BUF_LEN);
printf("char is %ld\n",buf);
printf("len is %ld\n",len);
//보통 이런 방식으로 사용.
/* loop over every read event until none remain */
while (i < len) {
struct inotify_event *event =
(struct inotify_event *) &buf[i];
printf ("wd=%d mask=%d cookie=%d len=%d dir=%s\n", event->wd, event->mask, event->cookie, event->len, (event->mask & IN_ISDIR) ? "yes" : "no");
/* if there is a name, print it */
if (event->len)
printf ("name=%s\n", event->name);
/* update the index to the start of the next event */
//printf("i is %d\n",i);
//printf("buf address is 0x%lx\n",&buf[i]);
if (event->mask && IN_ACCESS)
printf("the file was read\n");
i += sizeof (struct inotify_event) + event->len;
}
}
int ret;
ret = inotify_rm_watch(fd, wd);
if(ret)
perror("remove watch\n");
}
[21:45:06]>rm ./a.out ;gcc notify.c;./a.out
notify.c: In function ‘main’:
notify.c:45:21: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘char *’ [-Wformat=]
printf("char is %ld\n",buf);
~~^ ~~~
%s
file descriptor is 3
path is /home/now0930/test/ttt
char is 140729024548928
len is 16
wd=1 mask=32 cookie=0 len=0 dir=no
the file was read
char is 140729024548928
len is 16
wd=1 mask=32 cookie=0 len=0 dir=no
the file was read