我对bash脚本有点陌生,我有一个C ++程序通过一些命名管道与该bash脚本来回通信。我使用了inotifywait来监视文件夹中的新文件,并在添加新文件(以.job结尾)时通过管道将其发送到。
我正在用C ++程序将结果送回管道,如果结果是“退出”,则我希望bash脚本退出执行。
我试图通过出口1完成此操作,如下所示,但是这似乎并没有退出整个脚本。相反,在运行该出口之后,当我将另一个文件放入监视文件夹时,脚本结束。
我阅读了一些有关subshell的信息,想知道这是否与它们有关,以及有关如何退出整个脚本的任何建议。
DROP_FOLDER="$1"
DATA_FOLDER="$2"
OUTPUT_FOLDER="$3"
PATH_TO_EXECS="./tmp/"
PATH_TO_COMPLETED="../completed/"
# create pipes
read_pipe=/tmp/c_to_bash
write_pipe=/tmp/bash_to_c
if [[ ! -p $read_pipe ]]; then
mkfifo $read_pipe
fi
if [[ ! -p $write_pipe ]]; then
mkfifo $write_pipe
fi
# start c++ program
./tmp/v2 $DATA_FOLDER $OUTPUT_FOLDER $PATH_TO_EXECS "${write_pipe}" "${read_pipe}" &
# watch drop folder
inotifywait -m $DROP_FOLDER -e create -e moved_to |
while read path action file; do
# ends in .tga
if [[ "$file" =~ .*tga$ ]]; then
# move to image dir
mv "${DROP_FOLDER}${file}" "${DATA_FOLDER}${file}"
fi
# ends in .job
if [[ "$file" =~ .*job$ ]]; then
# pipe to dispatcher
echo "${DROP_FOLDER}${file}" > $write_pipe
# wait for result from pipe
if read line <$read_pipe; then
echo $line
# check for quit result
if [[ "$line" == 'quit' ]]; then
# move job file to completed
mv "${DROP_FOLDER}${file}" "${PATH_TO_COMPLETED}${file}"
# exit
exit 1
fi
# check for continue result
if [[ "$line" == 'continue' ]]; then
# move job file to completed
mv "${DROP_FOLDER}${file}" "${PATH_TO_COMPLETED}${file}"
fi
fi
fi
done
通常,您可以kill "$$"
从子外壳程序使用命令来终止主脚本($$
即使在子外壳程序中,脚本也将扩展为主外壳程序的pid,并且可以设置TERM
陷阱以捕获该信号)。
但看起来您实际上是想从右侧终止管道的左侧-即导致inotifywait
终止而无需等待,直到它向孤立管道写入内容并被杀死SIGPIPE
。为此,您可以inotifywait
使用pkill
以下命令明确地终止进程:
inotifywait -m /some/dir -e create,modify |
while read path action file; do
pkill -PIPE -P "$$" -x inotifywait
done
pkill -P
由父母选择;$$
应该是脚本的PID。这种解决方案当然不是万无一失的。也看看这个。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句