Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a pseudo-tty for reading output and writing to input

I am using fork() and execvp() to spawn a process that must believe it is connected to an interactive terminal for it to function properly.

Once spawned, I want to capture all the output from the process, as well as be able to send input to the process.

I suspect psuedo-ttys may help here. Does anyone have a snippet on how to do this?

like image 354
Ben Vitale Avatar asked Jul 29 '09 23:07

Ben Vitale


People also ask

What is pseudo-tty allocation?

A pseudo-TTY is a pair of character special files, a master file and a corresponding slave file. The master file is used by a networking application such as OMVS or rlogin. The corresponding slave file is used by the shell or the user's process to read and write terminal data.

What is a TTY output?

The tty command of terminal basically prints the file name of the terminal connected to standard input. tty is short of teletype, but popularly known as a terminal it allows you to interact with the system by passing on the data (you input) to the system, and displaying the output produced by the system.

Is Stdin a TTY?

Each TTY has its own stdin , stdout , and stderr streams connected to it. These are the streams provided to programs for them to read from ( stdin ) and write to ( stdout and stderr ). Like everything in UNIX, the tty is a file. Each instance of a terminal emulator has a different tty file associated with it.

What is a pseudo-terminal in Linux?

A pseudo-terminal is a special interprocess communication channel that acts like a terminal. One end of the channel is called the master side or master pseudo-terminal device, the other side is called the slave side.


1 Answers

You want to call forkpty(). From the man page:

#include <pty.h> /* for openpty and forkpty */

pid_t forkpty(int *amaster, char *name, struct termios *termp, struct winsize *winp);

Link with -lutil.

The forkpty() function combines openpty(), fork(), and login_tty() to create a new process operating in a pseudo-terminal. The file descrip‐ tor of the master side of the pseudo-terminal is returned in amaster, and the filename of the slave in name if it is not NULL. The termp and winp parameters, if not NULL, will determine the terminal attributes and window size of the slave side of the pseudo-terminal.

Your parent process talks to the child by reading and writing from the file descriptor that forkpty stores in "amaster" - this is called the master pseudo-terminal device. The child just talks to stdin and stdout, which are connected to the slave pseudo-terminal device.

like image 101
caf Avatar answered Sep 19 '22 12:09

caf