Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

如何用bash来实现这两个进程?

一个工作,两个进程,一个进程p1将处理好的文件放入文件夹project, 进程p2发现文件夹中有新的文件后,立即再处理,处理完成后,删除这个文件。

现在,如何实现p2能够立即知道有新文件了?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

有两个思路,一是直接循环遍历,如

while sleep 10; do
#do something you want ...
done

简单康粗暴且有效。

二是借助于inotify-tools.首先请确保inotify-tools已安装。

使用incron来调用处理脚本。

The user table rows have the following syntax (use one or more spaces between elements):

<path> <mask> <command>

Where:

  • <path>是文件系统路径(每个空格必须以反斜杠开头)
  • <mask>是符号(请参见inotify.h;使用逗号分隔符号)或事件的数字掩码
  • <command>是要在事件上运行的应用程序或脚本

该命令可能包含以下通配符:

  • $$ - 美元符号
  • $@ - 监视的文件系统路径
  • $# - 与事件相关的文件名
  • $% - 文本事件标志
  • $& - 数字事件标志

掩码可能还包含一个特殊符号IN_NO_LOOP,该符号禁用在处理事件期间发生的事件(以避免循环).

示例:'abc'每次在中更改文件时,都需要使用完整文件路径作为参数来运行程序/var/mail。解决方案之一如下:

/var/mail IN_CLOSE_WRITE abc $@/$#

也可以使用 inotifywait

如:

logOfChanges="/tmp/changes.log.csv" # 用于记录目录发生的变动.

# 后台执行 inotifywait 来监控 $DIR 目录发生的变动
inotifywait -mrcq $DIR > "$logOfChanges" &
IN_PID=$$

# 这里进行你希望的处理
...

# Kill and analyze
kill $IN_PID
while read entry; do
   # Split your CSV, but beware that file names may contain spaces too.
   # Just look up how to parse CSV with bash. :)
   path=... 
   event=...
   ...  # Other stuff like time stamps?
   # Depending on the event…
   case "$event" in
     SOME_EVENT) myHandlingCode path ;;
     ...
     *) myDefaultHandlingCode path ;;
done < "$logOfChanges"

inotifywait输入参数也可以使用--format,而不是-c

更多的相关信息请查阅 man inotifywaitman inotifywatch


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...