Linux终端与进程_学习笔记

   控制台 VS 终端

  1. 控制台是计算机的基本组成部分
  2. 终端是 连接 / 使用 计算机的附加设备
  3. 计算机只有一个控制台,但可以有多个终端
RX 发数据         TX 收数据
TTY -- 即:TeleType Writer 电传打字机,一种终端设备
现在演变为Linux的抽象概念,对于进程而言,TTY是一种输入输出设备。

终端类型

shell 对接从设备,主设备对接gnome_terminal(用户进程GUI)

伪终端程序设计(master) 

  • 创建 PTY 主从设备:master = posix_openpt(O_RDWR);
  • 获取主设备权限:
    • grantpt(master);                  //获取设备使用权限
    • unlockpt(master);                //解锁设备, 为读写做准备
  • 读写主设备
    • c = read(master, &rx, 1);
    • len = write(master, txbuf, strlen(txbuf));

伪终端程序设计(slave)

  • 打开PTY从设备:slave = open(path_to_slave, O_RDWR);
  • 读写从设备
    • write(slave, "Delphi\r", 7);
    • read(slave,buf, sizeof(buf)-1); 

sprintf()功能:

 #master.c
#define _XOPEN_SOURCE  600
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

int main()
{
    char rx = 0;
    char rxbuf[128] = {0};
    char txbuf[256] = {0};
    int master = 0;
    int c = 0;
    int i = 0;
    
    master = posix_openpt(O_RDWR); // gnome-terminal
    
    if( master > 0 )
    {
        grantpt(master);
        unlockpt(master);
        
        printf("Slave: %s\n", ptsname(master));
        
        while( (c = read(master, &rx, 1)) == 1 )
        {
            if( rx == '\r' )
            {
                rxbuf[i] = 0;
                sprintf(txbuf, "from slave: %s\r", rxbuf);   // show on screen
                write(master, txbuf, strlen(txbuf));   // keyboard input
                i = 0;
            }
            else
            {
                rxbuf[i++] = rx;
            }
        }
        
        close(master);
    }
    else
    {
        printf("create pty error...\n");
    }
    
    return 0;
}
#slave
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    int slave = open(argv[1], O_RDWR);   // shell
    
    if( slave > 0 )
    {
        char buf[256] = {0};
        char* data = "D.T.Software\r";
        int len = strlen(data);
        
        write(slave, data, len);
        
        sleep(1);
        
        len = read(slave, buf, sizeof(buf)-1);
        buf[(len > 0) ? len : 0] = 0;
        
        printf("Read: %s\n", buf);   // system(...)
        
        close(slave);
    }
    
    
    return 0;
}

 执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值