Show Table of Contents
A.2. 唤醒
很多应用程序都会扫描配置文件中的变更。在很多情况下,这种扫描的时间间隔是固定的,例如:每分钟。这可能是个问题,因为它强制将磁盘从低转速状态唤醒。最佳解决方案是找到合理的时间间隔,好的检查机制或者使用 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;
}
此方法的优点是您可执行不同的检查。
主要的局限是一个系统中可查看的次数是有限的。次数可在
/proc/sys/fs/inotify/max_user_watches 中获得,虽然该数字是可以更改的,但并不建议更改。此外,inotify 失败时,该代码必须返回不同的检查方法,通常意味着在源代码中会有很多 #if #define。
欲知有关 inotify 的详细信息,请参阅 inotify(7) man page。

Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.