많은 애플리케이션에서 구성 파일에서 변경 사항을 스캔합니다. 대부분의 경우 검사는 고정된 간격(예: 1분마다)으로 수행됩니다. 이 문제는 디스크가 스핀 다운에서 잠길 수 있기 때문에 문제가 될 수 있습니다. 가장 좋은 방법은 좋은 간격, 좋은 검사 메커니즘을 찾고, inotify 를 사용하여 변경 사항을 확인하고 이벤트에 대응하는 것입니다. ino tify는 파일 또는 디렉토리에 대한 다양한 변경 사항을 확인할 수 있습니다.
예를 들면 다음과 같습니다.
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd;
int wd;
int retval;
struct timeval tv;
fd = inotify_init();
/* checking modification of a file - writing into */
wd = inotify_add_watch(fd, "./myConfig", IN_MODIFY);
if (wd < 0) {
printf("inotify cannot be used\n");
/* switch back to previous checking */
}
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(fd + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
perror("select()");
else if (retval) {
printf("file was modified\n");
}
else
printf("timeout\n");
return EXIT_SUCCESS;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd;
int wd;
int retval;
struct timeval tv;
fd = inotify_init();
/* checking modification of a file - writing into */
wd = inotify_add_watch(fd, "./myConfig", IN_MODIFY);
if (wd < 0) {
printf("inotify cannot be used\n");
/* switch back to previous checking */
}
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(fd + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
perror("select()");
else if (retval) {
printf("file was modified\n");
}
else
printf("timeout\n");
return EXIT_SUCCESS;
}
Copy to ClipboardCopied!Toggle word wrapToggle overflow
이 접근 방식의 장점은 수행할 수 있는 다양한 검사입니다.
주요 제한 사항은 시스템에서 제한된 수의 시계만 사용할 수 있다는 것입니다. 번호는 /proc/sys/fs/inotify/max_user_watches 에서 얻을 수 있으며 변경할 수는 있지만 권장되지 않습니다. 또한 inotify 가 실패하는 경우 코드가 다른 검사 방법으로 대체되어야 합니다. 즉, 일반적으로 소스 코드에서 #if #define 가 많은 발생을 의미합니다.