DEV Community

Discussion on: Linux terminals, tty, pty and shell

Collapse
 
angelgruevski profile image
angelgruevski

"The std input, output and error of the bash will be set to be the pty slave."

What do you mean standard streams of bash will be set to be the pty slave? How are they set, is pty slave just another program and we use pipes to pass the data from pty slave to bash?

Collapse
 
napicella profile image
Nicola Apicella

Hi! I'll try to unpack your question:

  1. The pty slave is a device file
  2. Each program (of course that includes bash) is associated with at least 3 files descriptors (fd0 -> standard in, fd1 -> standard out, fd2 -> standard error). Normally fd0 is the file descriptor of the keyboard device file.

The std input, output and error of bash will be set to be the pty slave means:
the fd0, fd1 and fd2 of bash all have the same value, which is the file descriptor of the pty slave device file.

Collapse
 
maxfraguas profile image
Maximiliano • Edited

Hi Nicola,

First of all, let me thank you for your article, its was very useful and it guided me into other topics of study that clarified many doubts I had. Keep the good teaching!

Secondly, I still have two doubts.

You explained that when Bash opens a process (command), that process also sets its files descriptors to the same PTY slave file as Bash, and from there the TTY driver reads the output and sends it back to the terminal through the PTY Master.

I have two questions about this mechanism:

If a command (process) initiated by Bash, has its output set to the same PTY Slave as Bash, wouldn't Bash read the command's output as an input?

My other doubt is about a command whose output is piped as the input of a second command?
I'm guessing that in such cases, the stdout of the first command is set to a different intermediate file, which would be read as the stdin of the second command, then the second command writes its output to the same PTY slave file used by Bash. Am I close?

Thread Thread
 
napicella profile image
Nicola Apicella

Hello Maximiliano, thanks!

Regarding the first question - no the process standard input, out and error will be connected to the PTY slave. This seems to be one of the most tricky things to get, my guess is because the concept of a kernel module (like the pty module) might be confusing. I was thinking to write a follow up article on that.

About the second question - I do not think Bash needs to create temp files. I have always assumed that Bash duplicates the file descriptor so that the output of one program can be passed as standard input to next one in the pipe. This seems to be confirmed by the Bash source code: github.com/bminor/bash/blob/master...

That being said, pipes are a different beast. I do have an article which touches on that, but I haven't dived deep on they work behind the scene.