tsf144
tsf144

Reputation: 967

Bash timeout on 'read' command

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

Upvotes: 0

Views: 2673

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80961

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.

Upvotes: 3

Related Questions