实时读取两个文件

时间:2014-10-27 20:10:44

标签: bash

如果我有两个设备通过USB连接(在linux中),并希望同时读取它们。从本质上讲,它们永远不会终止,但我想在读取一行时读取它们(每行以\r\n结尾)。

这是Python中的样子:

from threading import Thread

usb0 = open("/dev/ttyUSB0", "r")
usb1 = open("/dev/ttyUSB1", "r")

def read0():
    while True: print usb0.readline().strip()

def read1():
    while True: print usb1.readline().strip()

if __name__ == '__main__':
    Thread(target = read0).start()
    Thread(target = read1).start()

有没有办法在bash中这样做。我知道你可以这样做:

while read -r -u 4 line1 && read -r -u 5 line2; do
  echo $line1
  echo $line2
done 4</dev/ttyUSB0 5</dev/ttyUSB1
然而,这实际上每隔几次切断我的部分线路。我真的更好奇,如果这是可能的并且并不真正需要它,因为使用Java或Python等现代编程语言进行线程化非常容易。

1 个答案:

答案 0 :(得分:7)

无法在bash中启动线程,但您可以为读取分叉两个后台作业。您需要将读取操作分散到两个单独的while构造中,并使用&符运算符&将它们放入后台:

#!/bin/bash

# Make sure that the background jobs will 
# get stopped if Ctrl+C is pressed
trap "kill %1 %2; exit 1" SIGINT SIGTERM

# Start a read loop for both inputs in background
while IFS= read -r line1 ; do
  echo "$line1"
  # do something with that line ...
done </dev/ttyUSB0 &

while IFS= read -r line2 ; do
  echo "$line2"
  # do something with that line ...
done </dev/ttyUSB1 &

# Wait for background processes to finish
wait %1 %2
echo "jobs finished"