使用C中的伪终端控制xterm

时间:2015-10-04 11:54:05

标签: c linux

我开始使用套接字编写一个简单的聊天应用程序(Linux)。我想启动一个单独的终端(xterm)进行聊天。所以我试着从聊天应用程序中分叉并执行xterm。但我无法使用聊天应用程序控制新的exec'ed xterm窗口。我使用了dup2(slave, STDIN_FILENO)STDOUT_FILENOSTDERR_FILENO,但新的xterm窗口仍未使用'slave'终端作为其I / O.

(我尝试了http://www.linusakesson.net/programming/tty/http://rachid.koucha.free.fr/tech_corner/pty_pdip.html和来自“Unix环境中的高级编程”的代码

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

2 个答案:

答案 0 :(得分:0)

这是我做类似的事情(在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

答案 1 :(得分:0)

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