如何创建用于读取输出和写入输入的伪 tty [英] How to create a pseudo-tty for reading output and writing to input

查看:44
本文介绍了如何创建用于读取输出和写入输入的伪 tty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 fork() 和 execvp() 来生成一个进程,该进程必须相信它已连接到交互式终端才能正常运行.

I am using fork() and execvp() to spawn a process that must believe it is connected to an interactive terminal for it to function properly.

一旦生成,我想捕获进程的所有输出,并且能够将输入发送到进程.

Once spawned, I want to capture all the output from the process, as well as be able to send input to the process.

我怀疑 psuedo-ttys 可能会在这里有所帮助.有没有人有关于如何做到这一点的片段?

I suspect psuedo-ttys may help here. Does anyone have a snippet on how to do this?

推荐答案

您想调用 forkpty().来自手册页:

You want to call forkpty(). From the man page:

#include /* 用于 openpty 和 forkpty */

#include <pty.h> /* for openpty and forkpty */

pid_t forkpty(int *amaster, char *name, struct termios *termp, structwinsize *winp);

pid_t forkpty(int *amaster, char *name, struct termios *termp, struct winsize *winp);

使用 -lutil 链接.

Link with -lutil.

forkpty() 函数结合了 openpty()、fork() 和 login_tty() 来创建一个在伪终端中运行的新进程.该文件描述了伪终端主端的tor在amaster中返回,如果它不为 NULL,则从属设备的文件名在 name 中.termp 和winp 参数,如果不为 NULL,将决定终端属性以及伪终端从机端的窗口大小.

The forkpty() function combines openpty(), fork(), and login_tty() to create a new process operating in a pseudo-terminal. The file descrip‐ tor of the master side of the pseudo-terminal is returned in amaster, and the filename of the slave in name if it is not NULL. The termp and winp parameters, if not NULL, will determine the terminal attributes and window size of the slave side of the pseudo-terminal.

您的父进程通过读取和写入 forkpty 存储在amaster"中的文件描述符来与子进程对话 - 这称为主伪终端设备.孩子只是与连接到从属伪终端设备的 stdin 和 stdout 对话.

Your parent process talks to the child by reading and writing from the file descriptor that forkpty stores in "amaster" - this is called the master pseudo-terminal device. The child just talks to stdin and stdout, which are connected to the slave pseudo-terminal device.

这篇关于如何创建用于读取输出和写入输入的伪 tty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆