🔥linux 下如何生成虛擬串口?
💧linux 中有虛擬終端的概念即 pty,pty 是成對的邏輯終端設備(有兩個終端組成,支持雙向收發),linux 系統調用原生支持生成虛擬終端。
💧無論是實體串口,還是虛擬串口,表現形式都是串口。
Ubuntu上,利用 socat 實現虛擬串口
安裝 socat
apt-get install socat
生成虛擬串口對
socat -d -d pty,b115200 pty,b115200
命令輸出內容
root@ioufev:/opt# socat -d -d pty,b115200 pty,b115200
2022/03/03 06:47:50 socat[178621] N PTY is /dev/pts/2
2022/03/03 06:47:50 socat[178621] N PTY is /dev/pts/3
2022/03/03 06:47:50 socat[178621] N starting data transfer loop with FDs [5,5] and [7,7]
在這個示例中 /dev/pts/2 和 /dev/pts/3 就是生成的虛擬串口對。
注意不同的機器生成的串口設備的編號可能不一樣,比如有的機器上可能會生成 /dev/pts/0 和 /dev/pts/1 等。
之后我們可以像訪問真實的串口設備一樣訪問這兩個虛擬串口了。
串口使用
查看輸出
cat /dev/pts/2
向串口輸入
echo 123 > /dev/pts/2
如果要一直輸出內容,可以使用 minicom
虛擬終端的概念
tty:終端設備的統稱
tty是Teletype或TeletypeWriter的縮寫,中文翻譯為電傳打字機。電傳打字機通常有鍵盤、收發報器和印字機等組成,是傳真機使用以前的通信設備,原理近似電報。后被顯示器和鍵盤所取代,所以現在叫終端比較合適。
終端是一種字符型設備,他有多種類型,通常使用tty來簡稱各種類型的終端設備。
目前,tty一般指控制終端(man 4 tty),設備文件是 /dev/ttyx 。
pty:虛擬終端
A pseudoterminal縮寫為pty,是虛擬終端或偽終端,可以在終端模擬器(terminal emulator)中運行,man pty查看。pty是成對的邏輯終端設備(即master和slave設備,對master的操作會反映到slave上,對slave的操作也會反映到master上),與實際物理設備無關。A pty is a pair of virtual character devices that provide a bidirectional communication channel. one end is called master; the other end is called the slave.
linux提供了兩套虛擬終端接口,BSD-style和System V-style,System V-style終端也被稱為UNIX 98 pseudoterminals,是目前使用的偽終端樣式。
An unused UNIX 98 pseudoterminal master is opened by calling posix_openpt(3). (This function opens the master clone device, /dev/ptmx; see pts(4).) After performing any program-specific initializations, changing the ownership and permissions of the slave device using grantpt(3), and unlocking the slave using unlockpt(3)), the corresponding slave device can be opened by passing the name returned by ptsname(3) in a call to open(2).
PTM指pseudoterminal master,PTS指pseudoterminal slave。
/dev/ptmx (UNIX 98 master clone device),所有主設備對應的設備文件都指向/dev/ptmx
/dev/pts/* (UNIX 98 slave devices)
串行端口終端
與計算機串行端口(RS-232)連接的終端設備,對應的設備文件名稱為/dev/tty+類型+設備編號,如/dev/ttyS0,S表示設備類型,0為指定類型下的設備編號。
這里的串行端口可以是通過硬件或軟件模擬的,如USB轉串口,虛擬串口。
