我有一个inotify
shell脚本,该脚本监视目录,并在有新文件进入时执行某些命令。我需要将此inotify
脚本放入并行化的进程中,因此脚本的执行不必等待以便在有多个文件进入目录时完成该过程。
我已经尝试使用nohup
,&
和xargs
来完成此任务。但是问题是,xargs
运行与多个进程相同的脚本,每当一个新文件进入时,所有正在运行的n进程都会尝试处理该脚本。但实际上,我只希望其中一个进程能够处理新文件,无论哪个空闲。类似工作者池之类的东西,无论工作者空闲还是空闲,都试图执行该任务。
这是我的shell脚本。
#!/bin/bash
# script.sh
inotifywait --monitor -r -e close_write --format '%w%f' ./ | while read FILE
do
echo "started script";
sleep $(( $RANDOM % 10 ))s;
#some more process which takes time when a new file comes in
done
我确实尝试使用xargs =>执行这样的脚本xargs -n1 -P3 bash sample.sh
因此,无论何时有新文件进入,由于P3,它都会被处理三次,但是理想情况下,我希望其中一个进程选择此任务,而这个任务永远是空闲的。
请说明如何解决此问题?
没有理由拥有一组空闲进程。当看到新文件出现时,只需为每个新文件运行一个。
#!/bin/bash
inotifywait --monitor -r -e close_write --format '%w%f' ./ |
while read -r file
do
echo "started script";
( sleep $(( $RANDOM % 10 ))s
#some more process which takes time when a new "$file" comes in
) &
done
请注意,将&
和括号加起来将sleep
分组,并在随后的处理中将其分成一个子外壳,然后我们可以将其作为背景。
此外,请注意我们始终喜欢read -r
和Correct Bash and shell script variable capitalization