*nix伪终端是如何工作的?主/从通道又是什么?

32
我想在Linux系统上用C语言编写一个简单的、愚蠢的X终端模拟器。起初,我只是认为需要使用popen打开一个shell并显示其输出。但检查了xterm和rxvt的代码后,发现情况有些复杂。
首先,我需要使用openpty打开一个伪终端。因此我查看了man手册,发现openpty会填充两个文件描述符:主描述符和从描述符。由于这些特殊文件具有与系统相关性,所以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;
}    

命令行程序“screen”使用这个,我想。有了它,您可以在主机上拥有已登录的控制台,如果您被踢出,可以重新登录并重新连接到该会话,并继续进行。这就是pty的本质。它具有与主机系统交互的通道和一个“反向通道”,您可以在外部告诉它要做什么(并查看结果)。我也没有任何实际实现的经验;我在“Linux应用程序开发”中读到了它们。在X下,我想有更多的窗口装饰,但基本原理应该是相同的。 - gbarry
2个回答

28
关于您提出的主/从问题,从我的系统上引用的openpty(3) man页中的pty(4) man页可以得知:
伪终端是一对字符设备,一个主设备和一个从设备。从设备为进程提供与tty(4)描述相同的接口。然而,所有提供tty(4)描述的接口的其他设备都有某种硬件设备作为其背后,而从设备则通过伪终端的主半部分由另一个进程操作。也就是说,在主设备上写入的任何内容都会作为输入传递给从设备,并且在从设备上写入的任何内容都会作为输入呈现在主设备上。
man页是您的好朋友。

7
我刚刚尝试了这个教程中的示例,它们对我来说很好用,我认为它们是解决问题的有趣起点。
编辑: 该教程简要解释了伪终端的功能。解释是逐步完成的,并且后跟示例。
以下示例展示如何创建一个新的伪终端,并将进程分成两部分,一部分写入伪终端的主侧,另一部分从伪终端的从侧读取。
#define _XOPEN_SOURCE 600 
#include <stdlib.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <unistd.h> 
#include <stdio.h> 
#define __USE_BSD 
#include <termios.h> 


int main(void) 
{ 
int fdm, fds, rc; 
char input[150]; 

fdm = posix_openpt(O_RDWR); 
if (fdm < 0) 
{ 
fprintf(stderr, "Error %d on posix_openpt()\n", errno); 
return 1; 
} 

rc = grantpt(fdm); 
if (rc != 0) 
{ 
fprintf(stderr, "Error %d on grantpt()\n", errno); 
return 1; 
} 

rc = unlockpt(fdm); 
if (rc != 0) 
{ 
fprintf(stderr, "Error %d on unlockpt()\n", errno); 
return 1; 
} 

// Open the slave PTY
fds = open(ptsname(fdm), O_RDWR); 
printf("Virtual interface configured\n");
printf("The master side is named : %s\n", ptsname(fdm));

// Creation of a child process
if (fork()) 
{ 
  // Father
 
  // Close the slave side of the PTY 
  close(fds); 
  while (1) 
  { 
    // Operator's entry (standard input = terminal) 
    write(1, "Input : ", sizeof("Input : ")); 
    rc = read(0, input, sizeof(input)); 
    if (rc > 0) 
    {
      // Send the input to the child process through the PTY 
      write(fdm, input, rc); 

      // Get the child's answer through the PTY 
      rc = read(fdm, input, sizeof(input) - 1); 
      if (rc > 0) 
      { 
        // Make the answer NUL terminated to display it as a string
        input[rc] = '\0'; 

        fprintf(stderr, "%s", input); 
      } 
      else 
      { 
        break; 
      } 
    } 
    else 
    { 
      break; 
    } 
  } // End while 
} 
else 
{ 
struct termios slave_orig_term_settings; // Saved terminal settings 
struct termios new_term_settings; // Current terminal settings 

  // Child

  // Close the master side of the PTY 
  close(fdm); 

  // Save the default parameters of the slave side of the PTY 
  rc = tcgetattr(fds, &slave_orig_term_settings); 

  // Set raw mode on the slave side of the PTY
  new_term_settings = slave_orig_term_settings; 
  cfmakeraw (&new_term_settings); 
  tcsetattr (fds, TCSANOW, &new_term_settings); 

  // The slave side of the PTY becomes the standard input and outputs of the child process 
  close(0); // Close standard input (current terminal) 
  close(1); // Close standard output (current terminal) 
  close(2); // Close standard error (current terminal) 

  dup(fds); // PTY becomes standard input (0) 
  dup(fds); // PTY becomes standard output (1) 
  dup(fds); // PTY becomes standard error (2) 

  while (1) 
  { 
    rc = read(fds, input, sizeof(input) - 1); 

    if (rc > 0) 
    { 
      // Replace the terminating \n by a NUL to display it as a string
      input[rc - 1] = '\0'; 

      printf("Child received : '%s'\n", input); 
    } 
    else 
    { 
      break; 
    } 
  } // End while 
} 

return 0; 
} // main

现在,您需要使用 #define _DEFAULT_SOURCE 1 而不是 #define __USE_BSD 来调用 man 3 termios。// 顺便说一下,要与具有 TUI 的应用程序交互,通常需要在父进程中将终端设置为原始模式,请参阅 https://dev59.com/V2025IYBdhLWcg3wtoVA#30632435 获取示例。 - user202729

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接