1. 程式人生 > >Linux 虛擬串列埠(可用於在本機上模擬串列埠進行除錯)

Linux 虛擬串列埠(可用於在本機上模擬串列埠進行除錯)

http://blog.sina.com.cn/s/blog_6cb543ef0100x90j.html

Python語言: #! /usr/bin/env python
#coding=utf-8

importpty
importos
importselect

defmkpty():
#開啟偽終端
master1,slave=pty.openpty()
slaveName1=os.ttyname(slave)
master2,slave=pty.openpty()
slaveName2=os.ttyname(slave)
print'\nslavedevice names: ',slaveName1,slaveName2
return
master1,master2

if__name__=="__main__":

master1,master2=mkpty()
whileTrue:
rl,wl,el=select.select([master1,master2],[],[],1)
formasterinrl:
data=os.read(master,128)
print"read %d data."%len(data)
ifmaster==master1:
os.write(master2,data)
else:
os.write(master1,data)
     程式名叫mkptych.py,在終端裡執行“python mkptych.py&”,這樣就可以生成一個基於pty(偽終端)的虛擬埠對,兩個裝置名會顯示在終端裡。然後就可以利用這兩個裝置名在本機上進行虛擬串列埠之類的除錯,
使用完後用ps檢視這個python程序的pid號,然後kill掉即可。     下面編寫一個用上述虛擬串列埠的使用程式:     //receive.c #include<stdio.h> #include<string.h> #include<malloc.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<termios.h> #include<math.h> #define MAX_BUFFER_SIZE512
int fd,s; intopen_serial() {     //這裡的/dev/pts/2是使用mkptych.py虛擬的兩個串列埠名字之一 fd = open("/dev/pts/2",O_RDWR|O_NOCTTY|O_NDELAY); if(fd == -1) { perror("open serial porterror!\n"); return -1; } printf("open/dev/ttyS0.\n"); return 0; } intmain() { char hd[MAX_BUFFER_SIZE],*rbuf; int flag_close,retv; struct termiosopt; retv =open_serial(); if(retv <0) { printf("Open serrial porterror!\n"); return -1; } tcgetattr(fd,&opt); cfmakeraw(&opt); cfsetispeed(&opt,B9600); cfsetospeed(&opt,B9600); tcsetattr(fd, TCSANOW,&opt); rbuf = hd; printf("Ready for receivingdata...\n"); while(1) { while((retv = read(fd,rbuf, 1)) > 0) printf( "%c ",*rbuf); } printf("\n"); flag_close =close(fd); if(flag_close ==-1) printf("Close the devicefailure!\n"); return 0; }      //send.c #include<stdio.h> #include<string.h> #include<malloc.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<termios.h> #define MAX_BUFFER_SIZE512 int fd,flag_close; intopen_serial() {     //這裡的/dev/pts/1是使用mkptych.py虛擬的兩個串列埠名字之一 fd = open("/dev/pts/1",O_RDWR | O_NOCTTY | O_NONBLOCK); if(fd == -1) { perror("open serial porterror!\n"); return -1; } printf("Open serial portsuccess!"); return 0; } int main(int argc, char*argv[]) { char sbuf[] = {"Hello, thisis a serial port test!\n"}; int retv; struct termiosoption; retv =open_serial(); if(retv <0) { perror("open serial porterror!\n"); return -1; } printf("Ready for sendingdata...\n"); tcgetattr(fd,&option); cfmakeraw(&option); cfsetispeed(&option,B9600); cfsetospeed(&option,B9600); tcsetattr(fd, TCSANOW,&option); int length =sizeof(sbuf); retv = write(fd, sbuf,length); if(retv == -1) { perror("Write dataerror!\n"); return -1; } printf("The number of charsent is %d\n", retv); return 0; }      編譯執行即可,呵呵