Linux 虛擬串口(可用於在本機上類比串口進行調試)__Linux

來源:互聯網
上載者:User

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


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

import pty
import os
import select

def mkpty():
    #開啟偽終端
    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()
    while True:
        rl, wl, el = select.select([master1,master2], [], [], 1)
        for master in rl:
            data = os.read(master, 128)
            print "read %d data." % len(data)
            if master==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");           

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.