我开始使用套接字编写一个简单的聊天应用程序(Linux)。我想启动一个单独的终端(xterm)来聊天。因此,我尝试从聊天应用程序中派生并执行一个xterm。但是我无法使用我的聊天应用程序来控制新的exec‘’ed xterm窗口。我使用了dup2(slave, STDIN_FILENO)、STDOUT_FILENO和STDERR_FILENO,但新的xterm窗口没有使用“从”终端进行I/O。
(我尝试了https://www.linusakesson.net/programming/tty/、https://rkoucha.fr/tech_corner/pty_pdip.html和“Unix环境中的高级编程”中的代码)
我也尝试过xterm -S选项。它正在工作,但我对使用它并不满意。
发布于 2016-10-22 16:34:21
下面是我如何做类似的事情(在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。
发布于 2016-10-23 00:33:36
您可以使用-e选项将命令直接传递给xterm。您可以创建聊天本身(从stdin读取并写入stdout等)在单独的二进制文件中,xterm只需要执行该二进制文件。
https://stackoverflow.com/questions/32933167
复制相似问题