许多应用会扫描配置文件以进行更改。在很多情况下,扫描以固定间隔执行,例如每分钟的一次。这可能会有问题,因为它会强制磁盘从启动中唤醒。最好的解决方法是找到一个良好的间隔、一个良好的检查机制,或使用 inotify 来检查对事件的更改。inotify 可以查看文件或目录的各种更改。
#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 Clipboard
Copied!
Toggle word wrap
Toggle overflow