在C中使用伪终端控制xterm

标签 c linux

我开始使用套接字编写一个简单的聊天应用程序(Linux)。我想启动一个单独的终端 (xterm) 进行聊天。所以我尝试从聊天应用程序中 fork 并执行 xterm。但我无法使用我的聊天应用程序控制新执行的 xterm 窗口。我使用了 dup2(slave, STDIN_FILENO)、STDOUT_FILENO 和 STDERR_FILENO,但是新的 xterm 窗口仍然没有使用“slave”终端它的 I/O。

(我尝试了 https://www.linusakesson.net/programming/tty/https://rkoucha.fr/tech_corner/pty_pdip.html 和“Unix 环境中的高级编程”中的代码)

我也尝试过 xterm -S 选项。它可以工作,但我对使用它不满意。

最佳答案

这是我如何做类似的事情(在 Linux 下用 C 语言):

// Open a pseudo-terminal master
int ptmx = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (ptmx == -1) {
    printf("Failed to open pseudo-terminal master-slave for use with xterm. Aborting...");
    quit(); // closes any open streams and exits the program
} else if (unlockpt(ptmx) != 0) {
    printf("Failed to unlock pseudo-terminal master-slave for use with xterm (errno. %d). Aborting...", errno);
    close(ptmx);
    quit();
}
else if (grantpt(ptmx) != 0) {
    printf("Failed to grant access rights to pseudo-terminal master-slave for use with xterm (errno. %d). Aborting...", errno);
    close(ptmx);
    quit();
}

// open the corresponding pseudo-terminal slave (that's us)
char *pts_name = ptsname(ptmx);
printf("Slave-master terminal: %s", pts_name);
int pts = open(pts_name, O_RDWR | O_NOCTTY);

// launch an xterm that uses the pseudo-terminal master we have opened
char *xterm_cmd;
asprintf(&xterm_cmd, "xterm -S%s/%d", pts_name, ptmx);
FILE *xterm_stdout = popen(xterm_cmd, "r");
if (xterm_stdout <= 0) {
    printf("Failed to open xterm process. Aborting...");
    ptmx = 0;
    close(ptmx);
    quit();
}

// Set the stdin / stdout to be the pseudo-terminal slave
dup2(pts, STDIN_FILENO);
dup2(pts, STDOUT_FILENO);

printf("This appears in the terminal window.\n");

现在,在终端中输入的任何内容都会被输入到程序的 stdin 中,并且程序输出到 stdout 的任何内容都会出现在终端中。您可以随意使用 readline 库、linenoise 甚至 curses

关于在C中使用伪终端控制xterm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933167/

相关文章:

c - 为什么要用 union 包装结构?

c - 多个 "\a"不起作用

c - Cortex M4 中的应用程序和固件分离

c++ - 是否可以强制Linux在释放后使虚拟内存失效

python - ctypes.ArgumentError : Don't know how to convert parameter

c - 如何将 const char* 指针传递给 fts_open()

linux - 将带有进程 ID 的窗口置于顶部并将其置于前台

java - Log4j 和 ${HOME} 变量 - HOME 未按预期扩展

arrays - 使用文件输入运行并行命令的 Bash 脚本

linux - 无法在 Linux 中构建 ParagraphVectors