控制台 VS 终端
-
控制台是计算机的基本组成部分
-
终端是 连接 / 使用 计算机的附加设备
-
计算机只有一个控制台,但可以有多个终端
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;
}
执行结果: