c언어 파일 이벤트 감시 (inotify)

프로그래밍/C, C++|2021. 2. 24. 11:56
반응형

파일이 생성, 변경, 삭제 되었을때 실시간으로 감지하여 특정 소스를 처리할 수 있습니다.

아래 소스를 백그라운드로 돌릴 경우 메세지 출력이 되지 않으나 동작은 되는것을 확인하였습니다.

파일 이벤트 종류는 아래 세가지 외에 더 있으므로 상세 감지가 필요하신 분은 기타 문서를 참고하시기 바랍니다.


#include <stdio.h>

#include <stdlib.h>

#include <errno.h>

#include <sys/types.h>

#include <sys/inotify.h>

#include <unistd.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, ".", // 현재 경로를 나타내며, 특정파일로 지정 가능합니다.

        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) {

                printf("The file %s was created.\n", event->name);

            } else if (event->mask & IN_DELETE) {

                printf("The file %s was deleted.\n", event->name);

            } else if (event->mask & IN_MODIFY) {

                printf("The file %s was modified.\n", event->name);

            }

        }

        i += EVENT_SIZE + event->len;

    }


    (void) inotify_rm_watch(fd, wd);

    (void) close(fd);


    return 0; 

}




[출처] https://stackoverflow.com/questions/13351172/inotify-file-in-c


반응형

댓글()