Inotify 等待目录中的大量文件

roh*_*lky 8 linux performance awk inotify

我想要做的是,监视一个目录(不是递归的,只有一个)以创建新文件,并将这些文件在写入时附加到一个大文件中。

正在写入的文件数量巨大,可能高达 50,000。

通过使用inotifywait,我正在监视目录,例如:

inotifywait -m -e create ~/folder | awk '($2=="CREATE"){print $3}' > ~/output.file
Run Code Online (Sandbox Code Playgroud)

所以我存储了创建的新文件的名称,~/output.file然后使用 for 循环

for FILE in `cat ~/output.file` 
do
    cat $FILE >> ~/test.out
done
Run Code Online (Sandbox Code Playgroud)

如果写入(创建)文件的速率~/folder类似于每秒 1 个文件,则它工作正常。

但是要求很大,而且创建文件的速度非常高,比如每分钟 500 个文件(甚至更多)。

我检查了~/folder进程完成后的文件数,但它与inotifywait输出不匹配。有 10-15 个文件的差异,各不相同。

此外,循环

for FILE in `cat ~/output.file`
do
done
Run Code Online (Sandbox Code Playgroud)

不会在~/output.file写入时处理所有文件。

任何人都可以建议我解决这个问题的优雅解决方案吗?

don*_*sti 6

您是否有特殊原因使用:

 | awk '($2=="CREATE"){print $3}' > ~/output.file
Run Code Online (Sandbox Code Playgroud)

而是inotifywait--format和这样的选项--outfile

如果我运行:

inotifywait -m --format '%f' -e create /home/don/folder/ --outfile /home/don/output.file
Run Code Online (Sandbox Code Playgroud)

然后打开另一个选项卡,cd~/folder和运行:

time seq -w 00001 50000 | parallel touch {}

real    1m44.841s
user    3m22.042s
sys     1m34.001s
Run Code Online (Sandbox Code Playgroud)

(所以我每分钟收到超过 500 个文件)一切正常,并且output.file包含50000我刚刚创建的所有文件名。
该过程完成将文件写入磁盘后,您可以将它们附加到您的test.out(假设您始终在~/folder)中:

xargs < /home/don/output.file cat >> final.file
Run Code Online (Sandbox Code Playgroud)

或者,read如果您想在创建文件时对其进行处理,请使用。因此,尽管~/folder你可以运行:

inotifywait -m --format '%f' -e create ~/folder | while read file; do cat -- "$file" >> ~/test.out; done
Run Code Online (Sandbox Code Playgroud)

注意在inotifywaitstable中,不能-m-t一起使用。最近添加了对使用这两个开关的支持,因此如果您inotify-tools从它构建,git您应该能够使用monitorwith timeout(指定在退出之前等待适当事件发生的时间)。我已经git在我的系统上测试了该版本(如果create在 2 秒内没有发生任何事件则退出)并且它工作正常:

inotifywait -m -t 2 --format '%f' -e create ~/folder | while read file; do cat -- "$file" >> ~/test.out; done
Run Code Online (Sandbox Code Playgroud)