本文介绍了如何在Linux中通过Screen应用程序创建可连接的PTY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to create C/C++ application, that creates new (virtual) device in /dev/xxx and will be able to connect with 'screen' application.

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

For example program running in loop, that creates new /dev/ttyABC. Then I'll use 'screen /dev/ttyABC', and when I send there some chars, then app send it back to the 'screen'.

我真的不知道从哪里开始.我在pty库上找到了一些引用,但我什至不知道,如果我有正确的方向.

I really don't know where start. I found some referencies on pty library but I don't even know, if I have right direction.

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

Could you help me? Where to look? Post example?Thanks

推荐答案

您可以使用 伪终端 通过 openpty 来实现这. openpty 返回一对通过其 stdout / stdin .一个的输出将出现在另一个的输入处,反之亦然.

You could use a Pseudoterminal via openpty to achieve this. openpty returns a pair of file descriptors (master and slave pty devices) that are connected to each other via their stdout / stdin. The output of one will appear at the input of another and vice-versa.

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

Using this (rough!) example...

#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;
}

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

... Echoing some text (in another terminal session) to the slave pty sends it to master's input. E.g. echo "Hello" > /dev/pts/2

这篇关于如何在Linux中通过Screen应用程序创建可连接的PTY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 15:58