Reading two files in real time

If I have two devices connected via USB (on linux) and you would like to read them at the same time. In fact, they never end, but I want to read them whenever they read a line (each line ends with \r\n).

Here's what it would look like in 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()

Is there any way to do this in bash. I know you can do this:

while read -r -u 4 line1 && read -r -u 5 line2; do
  echo $line1
  echo $line2
done 4</dev/ttyUSB0 5</dev/ttyUSB1

This, however, actually cuts off part of my line every couple of times per second. I am really curious if this is possible and is not really needed, as it is quite easy with threads in a modern programming language such as Java or Python.

+4
source share
1 answer

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"
+7

All Articles