Serial-Port

如何在 Linux 上使用串列埠,如管道或 netcat?

  • October 19, 2013

我有兩台電腦,有兩個串口:ttyS0 和 ttyUSB0。(實際上它們在同一台電腦上,但這只是為了測試)。埠通過零調製解調器電纜連接。我希望能夠簡單地將字節發送到一端並從另一端出來,反之亦然。為什麼以下不起作用?:

# set both serial ports to 9600 8n1
# `-parenb` means no parity,
# `-cstopb` means 1 stop bit
# cs8 means 8 bits at a time 
stty -F /dev/ttyUSB0 cs8 -cstopb -parenb 9600
stty -F /dev/ttyS0 cs8 -cstopb -parenb 9600

# in one terminal:
echo "asdf" > /dev/ttyUSB0

# in another terminal, this hangs and does nothing
cat < /dev/ttyS0

我可以netcat很容易地用和管道做類似的事情(下),所以我覺得像上面這樣的事情也應該是可能的。

mkfifo mypipe

# in one terminal
cat < mypipe

# in another. works as expected
echo "asdf" > mypipe

為什麼以下不起作用?

# in one terminal:
echo "asdf" > /dev/ttyUSB0

# in another terminal, this hangs and does nothing
cat < /dev/ttyS0

因為,作為一項規則,串列埠不緩衝數據。如果沒有客戶端應用程序接收登陸到串列埠的字節,它們將被簡單地丟棄。

作為實驗,嘗試在接收電腦上啟動minicomcu其他串列終端程序,然後echo在發送電腦上再次執行該命令。假設波特率和幀對齊,您應該會看到“asdf”出現在目的地。

引用自:https://unix.stackexchange.com/questions/96718