我想使用命名管道将一些数据发送到根进程。这是脚本,效果很好:
#!/bin/sh
pipe=/tmp/ntp
if [[ ! -p $pipe ]]; then
mknod -m 666 $pipe p
fi
while true
do
if read line <$pipe; then
/root/netman/extra/bin/ntpclient -s -h $line > $pipe 2>&1
fi
done
我实际上有几个像这样的脚本。我想将它们全部包含在一个脚本中。问题是执行在第一个“读取”时阻塞,并且我无法在单个进程中执行多个“读取”。难道我就没有什么可以做的吗?是否可以读取“非阻塞”bash?
Bash 的读取嵌入命令有一个 -t 参数来设置超时:
-t timeout
Cause read to time out and return failure if a complete line of input is not
read within timeout seconds. This option has no effect if read is not reading
input from the terminal or a pipe.
这应该可以帮助您解决这个问题。
Edit:
正如手册页所示,此解决方案的工作存在一些限制:如果 read 不是从终端或管道读取输入,则此选项无效。
因此,如果我在 /tmp 中创建一个管道:
mknod /tmp/pipe p
直接从管道读取不起作用:
$ read -t 1 </tmp/pipe ; echo $?
永远挂着。
$ cat /tmp/pipe | ( read -t 1 ; echo $? )
1
它正在工作,但猫没有退出。
解决方案是将管道分配给文件描述符:
$ exec 7<>/tmp/pipe
然后使用重定向从此文件描述符读取:
$ read -t 1 <&7 ; echo $?
1
Or the -u
的选项read
:
$ read -t 1 -u 7 ; echo $?
1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)