如何在 Linux 中创建可通过屏幕应用程序连接的 pty

How to create pty that is connectable by Screen app in Linux

本文关键字:应用程序 屏幕 连接 pty 可通过 创建 Linux      更新时间:2023-10-16

我想创建C/C++应用程序,该应用程序在/dev/xxx中创建新的(虚拟(设备,并且能够与"屏幕"应用程序连接。

例如,在循环中运行的程序,它会创建新的/dev/ttyABC。然后我将使用"screen/dev/ttyABC",当我向那里发送一些字符时,应用程序将其发送回"屏幕"。

我真的不知道从哪里开始。我在pty图书馆上找到了一些参考资料,但我什至不知道,如果我有正确的方向。

你能帮我吗?去哪里看?发布示例?谢谢

您可以通过openpty使用伪终端来实现此目的。 openpty返回一对文件描述符(主设备和从设备pty设备(,它们通过其stdout/stdin相互连接。一个的输出将出现在另一个的输入中,反之亦然。

使用这个(粗略的!(示例...

#include <fcntl.h>
#include <cstdio>
#include <errno.h>
#include <pty.h>
#include <string.h>
#include <unistd.h>
int main(int, char const *[])
{
  int master, slave;
  char name[256];
  auto e = openpty(&master, &slave, &name[0], nullptr, nullptr);
  if(0 > e) {
    std::printf("Error: %sn", strerror(errno));
    return -1;
  }
  std::printf("Slave PTY: %sn", name);
  int r;
  while((r = read(master, &name[0], sizeof(name)-1)) > 0) {
    name[r] = '';
    std::printf("%s", &name[0]);
  }
  close(slave);
  close(master);
  return 0;
}

。将一些文本(在另一个终端会话中(回显到从属 pty 会将其发送到master的输入。F.D. echo "Hello" > /dev/pts/2

根据@gmbeard提供的答案,我能够创建一个回显PTY设备,并通过屏幕和小对讲机连接到它。区别在于通过初始化termios结构来使用原始PTY设备。

这是代码

#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <cstdio>
#include <pty.h>
#include <termios.h>
#define BUF_SIZE (256)
int main(int, char const *[])
{
    int master, slave;
    char buf[BUF_SIZE];
    struct termios tty;
    tty.c_iflag = (tcflag_t) 0;
    tty.c_lflag = (tcflag_t) 0;
    tty.c_cflag = CS8;
    tty.c_oflag = (tcflag_t) 0;
    auto e = openpty(&master, &slave, buf, &tty, nullptr);
    if(0 > e) {
    std::printf("Error: %sn", strerror(errno));
    return -1;
    }
    std::printf("Slave PTY: %sn", buf);
    int r;
    while ( (r = read(master, buf, BUF_SIZE)) > 0 )
    {
        write(master, buf, r);
    }
    close(slave);
    close(master);
    return 0;
}