4

Suppose I want to invoke some command on all files in a directory and set a watch to invoke that command on all files that get created in that directory. If I do:

while( ( sdi = readdir( d )) != NULL ) { ... }
closedir( d );
/* Files created here will be missed */
inotify_add_watch( ... );

then some files will potentially be missed. If I call inotify_add_watch() before the readdir(), files may be acted on twice (it would require a fair bit of infrastructure to prevent acting twice, and it seems that the edge cases would be difficult to handle). Is there a simple way to avoid having to record the names of all files worked on during the readdir loop and comparing those to the names returned in the inotify_event structure? I can minimize the amount of necessary comparisons with:

while( ( sdi = readdir( d )) != NULL ) { ... }
inotify_add_watch( ... );
while( ( sdi = readdir( d )) != NULL ) { /* record name */ ... }
closedir( d );

And usually the second readdir() loop will do nothing, but this feels like a bad hack.

4

1 回答 1

3

你根本做不到。您破解的越多,您获得的比赛条件就越多。

最简单的实际工作解决方案是在使用之前设置手表opendir(),并保留已使用名称(或其哈希值)的列表(集合)。

但这也不完美。用户可以在文本编辑器中打开文件;你修复它,用户保存它并且目录包含未修复的文件,尽管它在你的列表中。

最好的方法是让程序能够通过内容实际区分使用过的文件。换句话说,您设置 watch,在readdir()结果上调用命令,然后在 inotify 结果上调用它,并让命令本身知道文件是否已经正常。

于 2011-08-23T08:27:37.443 回答