简体   繁体   中英

control xterm using pseudo terminal in C

I started writing a simple chat application (Linux) using sockets. I wanted to launch a separate terminal (xterm) for a chat. So I tried to fork and exec an xterm from the chat application. But I am unable to control the new exec'ed xterm window using my chat application. I used dup2(slave, STDIN_FILENO) , STDOUT_FILENO and STDERR_FILENO , but still, the new xterm window is not using the 'slave' terminal for its I/O.

(I tried https://www.linusakesson.net/programming/tty/ , https://rkoucha.fr/tech_corner/pty_pdip.html and code from "Advanced programming in Unix environment)

I have also tried xterm -S option. It is working, but I am not satisfied using it.

Here is how I do something similar (in C under Linux):

// 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");

Now anything getting entered in the terminal is fed to the program's stdin , and anything that the program outputs to stdout appears in the terminal. You can use the readline library, linenoise , or even curses at will.

You can pass a command directly to xterm using -e option. You can create the chat itself (read fron stdin and write to stdout etc.) in a separate binary and xterm will only need to execute that binary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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