首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C中使用伪终端控制xterm

在C中使用伪终端控制xterm
EN

Stack Overflow用户
提问于 2015-10-04 19:54:05
回答 2查看 660关注 0票数 0

我开始使用套接字编写一个简单的聊天应用程序(Linux)。我想启动一个单独的终端(xterm)来聊天。因此,我尝试从聊天应用程序中派生并执行一个xterm。但是我无法使用我的聊天应用程序来控制新的exec‘’ed xterm窗口。我使用了dup2(slave, STDIN_FILENO)STDOUT_FILENOSTDERR_FILENO,但新的xterm窗口没有使用“从”终端进行I/O。

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

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

EN

回答 2

Stack Overflow用户

发布于 2016-10-22 16:34:21

下面是我如何做类似的事情(在Linux下的C中):

代码语言:javascript
复制
// 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

票数 0
EN

Stack Overflow用户

发布于 2016-10-23 00:33:36

您可以使用-e选项将命令直接传递给xterm。您可以创建聊天本身(从stdin读取并写入stdout等)在单独的二进制文件中,xterm只需要执行该二进制文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32933167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档