gpt4 book ai didi

c - *nix 伪终端如何工作?什么是主/从 channel ?

转载 作者:IT王子 更新时间:2023-10-29 00:14:54 25 4
gpt4 key购买 nike

我想在 Linux 系统上用 C 编写一个简单、愚蠢的 X 终端仿真器。

起初,我只是想我必须打开一个 shell 并显示它的输出。我检查了 xterm 和 rxvt 代码,看起来有点复杂。

首先,我必须用 openpty 打开一个伪终端。所以我查看了手册页,发现 openpty 填充了 2 个文件描述符,主从。xterm 和 rxvt 代码都是困惑的,因为这些特殊文件的系统依赖性。

我理解 termios 的东西:它只是一堆关于终端转义码的信息。我真正不明白的是:我应该如何处理主/从文件描述符?

打开终端、登录、在 shell 上执行“ls”的示例程序会很棒。

(英语不是我的母语,请原谅我最后的错误)

编辑:这是我想出的示例代码:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pty.h>
#include <utmp.h>
#include <ctype.h>

void
safe_print (char* s)
{
while(*s) {
if(*s == '\n')
putchar("\n");
else if(iscntrl(*s))
printf("\\e(%d)", *s);
else
putchar(*s);
s++;
}
}


int
main (int argc, char** argv)
{
char buf[BUFSIZ] = {0};
int master;
int ret = forkpty(&master, NULL, NULL, NULL);

if(ret == -1)
puts("no fork"), exit(0);

if(!ret) {
execl("/bin/sh", "sh", NULL);
exit(0);
}

sleep(1); /* let the shell run */


if(argc >= 2) {
write(master, argv[1], strlen(argv[1]));
write(master, "\n", 1);
} else {
write(master, "date\n", sizeof "date\n");
}


while(1) {
switch(ret = read(master, buf, BUFSIZ)) {
case -1:
puts("error!");
exit(1);
break;
case 0:
puts("nothing.."), sleep(1);
break;
default:
buf[ret] = '\0';
safe_print(buf);

}
}

close(master);

return 0;
}

最佳答案

关于您问题的主/从部分,来自 pty(4)手册页(引用 self 系统上的 openpty(3) 手册页):

A pseudo terminal is a pair of character devices, a master device and a slave device. The slave device provides to a process an interface identical to that described in tty(4). However, whereas all other devices which provide the interface described in tty(4) have a hardware device of some sort behind them, the slave device has, instead, another process manipulating it through the master half of the pseudo terminal. That is, anything written on the master device is given to the slave device as input and anything written on the slave device is presented as input on the master device.

手册页是您的 friend 。

关于c - *nix 伪终端如何工作?什么是主/从 channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/476354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com