Bash timeout on 'read' command

狂风中的少年 提交于 2019-12-12 03:22:09

问题


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

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

回答1:


From section 4.2 Bash Builtin Commands of the Bash Reference Manual:

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

...

-t timeout

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.



来源:https://stackoverflow.com/questions/27508467/bash-timeout-on-read-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!