“读取"命令上的 Bash 超时 [英] Bash timeout on 'read' command

查看:49
本文介绍了“读取"命令上的 Bash 超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 bash 脚本,它向串行发送命令并读回值.问题是当我没有取回价值时,它可能会卡住.

I have a pretty simple bash script that sends command to serial and reads thee value back. The problem is when I don't get a value back,, it can get stuck.

echo BC > /dev/ttyS1
read line < /dev/ttyS1
echo $line

我使用了带有超时的 cat 命令,但不能使用与读取"相同的技术,因为如果我将进程发送到后台,我永远不会在退出时取回值.猫"在大多数情况下都有效,但我不确定这是否是最可靠的方法.

I have used the cat command with a timeout, but cannot use the same technique with 'read', because if I send the process to the background, I never get value back on exit. 'cat' works for the most part, but i'm not sure if this is the most robust way to do this.

echo BC > /dev/ttyS1
cat /dev/ttyS1 &
    pid=$!
    sleep 0.1
    kill -9 $pid

推荐答案

来自 4.2 Bash 内置命令:

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name…]

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]

...

-t 超时

如果在超时秒内没有读取完整的输入行,则导致读取超时并返回失败.timeout 可以是一个十进制数,小数点后面有小数部分.此选项仅在 read 从终端、管道或其他特殊文件读取输入时有效;从常规文件读取时它不起作用.如果超时为 0,如果输入在指定的文件描述符上可用,则 read 返回成功,否则返回失败.如果超时,则退出状态大于 128.

Cause read to time out and return failure if a complete line of input is not read within timeout seconds. timeout may be a decimal number with a fractional portion following the decimal point. This option is only effective if read is reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If timeout is 0, read returns success if input is available on the specified file descriptor, failure otherwise. The exit status is greater than 128 if the timeout is exceeded.

这篇关于“读取"命令上的 Bash 超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆