简体   繁体   English

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

[英]Simplest way to get a PTY in Linux C++

I am programming something that needs an interface to Bash. At first I thought I could just use popen or QProcess.我正在编写需要 Bash 接口的程序。起初我以为我可以只使用 popen 或 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. (我正在使用 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.我在 GNU 标准 C 库中找到了一些类似 forkpty()、openpty() 等的东西,但无法弄清楚如何使用它们或找到任何好的示例,即使在阅读了它们相应的联机帮助页之后也是如此。 Literally, all this part of my program needs to do is be able to read/write from a tty running /bin/bash.从字面上看,我程序的这一部分需要做的就是能够从运行 /bin/bash 的 tty 读取/写入。 Is it really that simple, or is there more to it than meets the eye?真的有那么简单,还是比看上去的要复杂得多?

If so, can anyone please provide a concise example on how to do this?如果是这样,谁能提供一个简明的例子来说明如何做到这一点? Thanks in advance: EDIT: Here's the header file I've come up with!在此先感谢:编辑:这是我想出的 header 文件!

If you have Python, try something like:如果您有 Python,请尝试以下操作:

QProcess p;
p.start("python", {"-c", "import pty; pty.spawn("/bin/bash")})"

Consider the option of running /bin/sh -s , which means "read commands from standard input".考虑运行/bin/sh -s的选项,这意味着“从标准输入读取命令”。 That removes the need to emulate a terminal.这消除了模拟终端的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM