这里有一个例子,它运行两个作为同一shell脚本函数实现的子进程…其中一个子进程生成1到5的数字(在打印之间休眠),第二个子进程从固定文件描述符(5)读取(它是第一个FD的STDOUT重定向到的),乘以2后再次打印。主进程将该第二个进程的STDOUT重定向到另一个固定文件描述符(6),然后在循环中从其中一个读取。
它的工作原理与您在C代码中使用pipe(2)系统调用创建的fd对基本相同。要了解发生了什么,请在strace -f下运行脚本!
Bash版本为4.2.24(1),正在Ubuntu/x86上运行。
[ubuntu /home/chris]
$ bash --version
GNU bash, version 4.2.24(1)-release (i686-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software
There is NO WARRANTY, to the extent permitted by law.
脚本的输出:
[ubuntu /home/chris]
$ ./read_from_fd.sh
Got number 2.
Got number 4.
Got number 6.
Got number 8.
Got number 10.
源代码:
#!/bin/bash
generate_five_numbers() {
for n in `seq 5` ; do
echo $n
sleep 2
done
}
multiply_number_from_fd5_by_two() {
while read n <&5 ; do
echo "$(( $n * 2 ))"
done
}
exec 5< <( generate_five_numbers )
exec 6< <( multiply_number_from_fd5_by_two )
while read n <&6 ; do
echo "Got number $n."
done
运行时的进程树:
──read_from_fd.sh(8118)─┬─read_from_fd.sh(8119)───sleep(8123)
└─read_from_fd.sh(8120)
mktemp
来生成一个唯一的名称。 - Alexandre C.