bash 在 Linux C++ 中获取 PTY 的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2155314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:36:25  来源:igfitidea点击:

Simplest way to get a PTY in Linux C++

c++linuxbashqtpty

提问by

I am programming something that needs an interface to Bash. At first I thought I could just use popen or QProcess. ( I'm using QT C++ ) They work fine but I can't get them to run Bash in a tty, which you need if you are going to use anything like sudo, which requires a tty/pty to accept a password.

我正在编写一些需要 Bash 接口的东西。起初我以为我可以只使用 popen 或 QProcess。(我正在使用 QT C++)它们工作正常,但我无法让它们在 tty 中运行 Bash,如果您要使用诸如 sudo 之类的任何东西,您需要它,它需要一个 tty/pty 来接受密码。

I found some things like forkpty(), openpty(), etc. in the GNU Standard C libraries, but could not figure out how to use them or find any good examples, even after reading their corresponding manpages. Literally, all this part of my program needs to do is be able to read/write from a tty running /bin/bash. Is it really that simple, or is there more to it than meets the eye?

我在 GNU 标准 C 库中发现了一些像 forkpty()、openpty() 等的东西,但无法弄清楚如何使用它们或找到任何好的例子,即使在阅读了它们相应的手册页之后。从字面上看,我程序的这部分需要做的就是能够从运行 /bin/bash 的 tty 读取/写入。真的那么简单,还是有比表面更重要的东西?

If so, can anyone please provide a concise example on how to do this? Thanks in advance! EDIT: Here'sthe header file I've come up with!

如果是这样,任何人都可以提供一个简洁的例子来说明如何做到这一点?提前致谢!编辑:这是我想出的头文件!

回答by rohanpm

Consider the option of running /bin/sh -s, which means "read commands from standard input". That removes the need to emulate a terminal.

考虑 running 选项/bin/sh -s,这意味着“从标准输入读取命令”。这消除了模拟终端的需要。