我有两个bash脚本。 一个脚本写入fifo。第二个从fifo读取,但在第一个结束后写入。
但是有些东西不起作用。我不明白问题出在哪里。这是代码。
第一个脚本是(作者):
#!/bin/bash
fifo_name="myfifo";
# Se non esiste, crea la fifo;
[ -p $fifo_name ] || mkfifo $fifo_name;
exec 3<> $fifo_name;
echo "foo" > $fifo_name;
echo "bar" > $fifo_name;
第二个脚本是(读者):
#!/bin/bash
fifo_name="myfifo";
while true
do
if read line <$fifo_name; then
# if [[ "$line" == 'ar' ]]; then
# break
#fi
echo $line
fi
done
有人能帮帮我吗? 谢谢
答案 0 :(得分:7)
将第二个脚本替换为:
#!/bin/bash
fifo_name="myfifo"
while true
do
if read line; then
echo $line
fi
done <"$fifo_name"
这只打开一次fifo并从中读取每一行。
答案 1 :(得分:2)
如果您希望在读者实际运行时控制fifo访问时间,那么您的设置问题就是您在错误的脚本中创建了fifo。为了纠正这个问题,你需要做这样的事情:
读者:fifo_read.sh
#!/bin/bash
fifo_name="/tmp/myfifo" # fifo name
trap "rm -f $fifo_name" EXIT # set trap to rm fifo_name at exit
[ -p "$fifo_name" ] || mkfifo "$fifo_name" # if fifo not found, create
exec 3< $fifo_name # redirect fifo_name to fd 3
# (not required, but makes read clearer)
while :; do
if read -r -u 3 line; then # read line from fifo_name
if [ "$line" = 'quit' ]; then # if line is quit, quit
printf "%s: 'quit' command received\n" "$fifo_name"
break
fi
printf "%s: %s\n" "$fifo_name" "$line" # print line read
fi
done
exec 3<&- # reset fd 3 redirection
exit 0
编写者:fifo_write.sh
#!/bin/bash
fifo_name="/tmp/myfifo"
# Se non esiste, exit :);
[ -p "$fifo_name" ] || {
printf "\n Error fifo '%s' not found.\n\n" "$fifo_name"
exit 1
}
[ -n "$1" ] &&
printf "%s\n" "$1" > "$fifo_name" ||
printf "pid: '%s' writing to fifo\n" "$$" > "$fifo_name"
exit 0
操作:(在第一个终端启动阅读器)
$ ./fifo_read.sh # you can background with & at end
(在第二个终端启动编写器)
$ ./fifo_write.sh "message from writer" # second terminal
$ ./fifo_write.sh
$ ./fifo_write.sh quit
在第一个终端输出:
$ ./fifo_read.sh
/tmp/myfifo: message from writer
/tmp/myfifo: pid: '28698' writing to fifo
/tmp/myfifo: 'quit' command received
答案 2 :(得分:1)
以下脚本应该完成这项工作:
#!/bin/bash
FIFO="/tmp/fifo"
if [ ! -e "$FIFO" ]; then
mkfifo "$FIFO"
fi
for script in "$@"; do
echo $script > $FIFO &
done
while read script; do
/bin/bash -c $script
done < $FIFO
给出两个脚本a.sh和b.sh,其中两个脚本都通过&#34; a&#34;和&#34; b&#34;对于stdout,分别得到以下结果(假设上面的脚本名为test.sh):
./test.sh /tmp/a.sh /tmp/b.sh
a
b
最佳, 儒略