gpt4 book ai didi

具有非阻塞读取的 Bash 脚本

转载 作者:行者123 更新时间:2023-11-29 08:53:59 26 4
gpt4 key购买 nike

我想使用命名管道将一些数据发送到根进程。这是脚本,效果很好:

#!/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

我实际上有几个这样的脚本。我想将它们全部包含在一个脚本中。问题是第一次“读取”时执行 block ,我无法在单个进程中执行多个“读取”。没有什么我可以做的吗?是否可以读取“非阻塞”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.

这应该可以帮助您解决这个问题。

编辑:

如手册页所示,此解决方案的工作有一些限制:如果 read 不是从终端或管道读取输入,则此选项无效。

所以如果我在/tmp 中创建一个管道:

mknod /tmp/pipe p

直接从管道读取是行不通的:

$ read -t 1 </tmp/pipe  ; echo $?

永远挂起。

$ cat /tmp/pipe | ( read -t 1 ; echo $? )
1

它正在工作,但 cat 没有退出。

一个解决方案是将管道分配给一个文件描述符:

$ exec 7<>/tmp/pipe

然后使用重定向从这个文件描述符中读取:

$ read -t 1 <&7  ; echo $?
1

或者read-u选项:

$ read -t 1 -u 7  ; echo $?
1

关于具有非阻塞读取的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4874993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com