bash 使用 inotify-tools 作为守护进程处理数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10533200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Processing data with inotify-tools as a daemon
提问by Valentin Radu
I have a bash script that processes some data using inotify-tools to know when certain events took place on the filesystem. It works fine if run in the bash console, but when I try to run it as a daemon it fails. I think the reason is the fact that all the output from the inotifywaitcommand call goes to a file, thus, the part after | whiledoesn't get called anymore. How can I fix that? Here is my script.
我有一个 bash 脚本,它使用 inotify-tools 处理一些数据,以了解文件系统上何时发生了某些事件。如果在 bash 控制台中运行它可以正常工作,但是当我尝试将它作为守护程序运行时它会失败。我认为原因是inotifywait命令调用的所有输出都转到一个文件中,因此之后的部分| while不再被调用。我该如何解决?这是我的脚本。
#!/bin/bash
inotifywait -d -r \
-o /dev/null \
-e close_write \
--exclude "^[\.+]|cgi-bin|recycle_bin" \
--format "%w:%&e:%f" \
|
while IFS=':' read directory event file
do
#doing my thing
done
So, -dtells inotifywaitto run as daemon, -rto do it recursively and -ois the file in which to save the output. In my case the file is /dev/nullbecause I don't really need the output except for processing the part after the command (| while...)
因此,-d告诉inotifywait作为守护程序运行,-r递归执行,并且-o是保存输出的文件。就我而言,该文件是/dev/null因为除了处理命令 ( | while...)之后的部分之外,我实际上并不需要输出
回答by larsks
You don't want to run inotify-waitas a daemon in this case, because you want to continue process output from the command. You want to replace the -dcommand line option with -m, which tells inotifywaitto keep monitoring the files and continue printing to stdout:
inotify-wait在这种情况下,您不想作为守护程序运行,因为您想继续处理命令的输出。你想用 替换-d命令行选项-m,它告诉inotifywait继续监视文件并继续打印到stdout:
-m, --monitor
Instead of exiting after receiving a single event, execute
indefinitely. The default behaviour is to exit after the
first event occurs.
If you want things running in the background, you'll need to background the entire script.
如果您希望事情在后台运行,则需要将整个脚本设为后台。
回答by Jonathan MacDonald
Here's a solution using nohup: (Note in my testing, if I specified the -o the while loop didn't seem to be evaluated)
这是一个使用 nohup 的解决方案:(注意在我的测试中,如果我指定了 -o,while 循环似乎没有被评估)
nohup inotifywait -m -r \
-e close_write \
--exclude "^[\.+]|cgi-bin|recycle_bin" \
--format "%w:%&e:%f" \
|
while IFS=':' read directory event file
do
#doing my thing
done >> /some/path/to/log 2>&1 &

