开发者

How i can read tty file with timeout?

I have tty device in /dev , where I send AT commands. I wan开发者_JS百科t to read line by line and stop reading file after timeout.


You can use the program stty to configure the tty device. To see the settings for terminal /dev/ttyS0, try

stty -a -F /dev/ttyS0

The default settings regarding timeout are min = 1; time = 0, which means that the reading program will read until at least one character has been read and there is no timeout. Using e.g.

stty -F /dev/ttyS0 min 0 time 10

the reading program (e.g. cat) will finish reading after one second whether anything has been read or not. The unit for the parameter time is tenths of a second; you can check out man stty for more information.


Compiling some info from here, you can have a script in the sorts of:

#!/bin/bash

#SPECIFYING THE SERIAL PORT
SERIAL=ttyS0

#SETTING UP AN ERROR FLAG
FLAG="GO"

#OPENING SERIAL PORT FOR READING
exec 99</dev/${SERIAL} 

#READING FROM SERIAL
while ["${FLAG}" == "GO" ]
do 
    #IF NO INPUT IS READ AFTER 5 SECONDS, AN ERROR FLAG IS RAISED
    read -t 5 INPUT <&99
    STATUS=$?
    if test $STATUS -ne 0;
    then
      FLAG="ERROR"
    fi
done

#CLOSING SERIAL PORT
exec 99>&-

While FLAG==GO, the script will read one line at a time from the serial port. The STATUS variable gets the return of READ command. According to the manual READ will return anything different than 0 if the specified timeout is reached; when that happens, FLAG is updated, exiting the read loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜