c++ - 如何在 Linux 中创建可通过 Screen 应用程序连接的 pty

标签 c++ linux

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

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

我真的不知道从哪里开始。我在 pty 库上找到了一些引用文献,但我什至不知道我的方向是否正确。

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

最佳答案

你可以使用 Pseudoterminal通过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: %s\n", strerror(errno));
    return -1;
  }

  std::printf("Slave PTY: %s\n", name);

  int r;

  while((r = read(master, &name[0], sizeof(name)-1)) > 0) {
    name[r] = '\0';
    std::printf("%s", &name[0]);
  }

  close(slave);
  close(master);

  return 0;
}

... 将某些文本(在另一个终端 session 中)回显到从属 pty 将其发送到 master 的输入。例如。 echo "Hello">/dev/pts/2

关于c++ - 如何在 Linux 中创建可通过 Screen 应用程序连接的 pty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33237254/

相关文章:

linux - Ansible - 使用以下代码时无法找到 .bash_profile 文件

c++ - CMake 链接到错误版本的库

c - 不同线程中的多个 epoll_wait 接收不是为它们设计的事件

c++ - 查找显示链表的错误

c++ - libQt5Core.so : undefined reference to `__cxa_throw_bad_array_new_length@CXXABI_1. 3.8

c# - 在 C# 中使用 P/Invoke 注册 _set_purecall_handler 函数

C++ 非类型参数包扩展

python - 打印出矩阵中的值

c++ - 如何在不同的目标平台上以编程方式巧妙地注册 32 位 COM/DLL 组件?

c++ - 无法在函数内部为 cv::Mat 赋值