如何在 Linux 上使用串行端口,如管道或 netcat?

use*_*135 4 serial-port

我有两台带有两个串行端口的计算机: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
Run Code Online (Sandbox Code Playgroud)

我可以netcat很容易地使用和管道做类似的事情(如下),所以我觉得上面的事情也应该是可能的。

mkfifo mypipe

# in one terminal
cat < mypipe

# in another. works as expected
echo "asdf" > mypipe
Run Code Online (Sandbox Code Playgroud)

ewh*_*hac 6

为什么下面的不起作用?

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

# in another terminal, this hangs and does nothing
cat < /dev/ttyS0
Run Code Online (Sandbox Code Playgroud)

因为,通常情况下,串行端口不缓冲数据。如果没有客户端应用程序接收登陆串行端口的字节,它们将被简单地丢弃。

作为实验,尝试在接收计算机上启动minicomcu或其他串行终端程序,然后echo在发送计算机上再次运行该命令。假设波特率和帧对齐,您应该看到“asdf”出现在目的地。