2014-10-27 79 views
4

如果我有兩個通過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)進行線程化非常簡單。

回答

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

謝謝查殺無法終止。我正要考慮這件事。這比我認爲可以發揮作用的效果更好。我不確定如何啓動*兩個*後臺作業,因爲我在執行'cat file1& cat file2&',非常感謝! – dylnmc 2014-10-27 20:44:56

+0

不客氣! :) – hek2mgl 2014-10-27 20:47:41

+1

那麼;不要毀了你的樂趣,但是你可以做'cat/dev/ttyUSB0&cat/dev/ttyUSB1&':P – dylnmc 2014-10-27 20:48:17