开发者

How do I avoid this race condition with readdir/inotify?

开发者 https://www.devze.com 2023-03-29 20:10 出处:网络
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:

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开发者_StackOverflow社区 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.


You simply can't. The more you hack, the more race conditions you'll get.

The simplest actually working solution is to set the watch before using opendir(), and keep a list (set) of already used names (or their hashes).

But this isn't perfect either. User can have the file open in a text editor; you fix it, user saves it and the directory contains unfixed file anyway, though it's on your list.

The best method would be to be able for the program to actually distinguish used files by their content. In other words, you set watch, call command on readdir() results, then call it on inotify results and let the command itself know whether the file is fine already or not.

0

精彩评论

暂无评论...
验证码 换一张
取 消