I’ve been trying to figure out how TTY drivers works for a while now (with full understanding each kernel’s implementation may be different), and came across a nice article: The TTY demystified
I notice however that it claims xterm does not have a stdin, stdout or stderr. How does xterm and other terminal emulators get the input from bash and other child processes so it can print to the window? Does the terminal emulator have a connection to a TTY driver at all?
I don’t believe the claim that
xterm(1)has nostdin,stdout, orstderrmakes much sense. And, just skimming that article, I think they were left blank on the diagram because they didn’t figure much into what he was describing.You can check your own terminals’ file descriptors easily enough. The
urxvt(1)terminals that I normally use look like this:An
xterm(1)I started from one of thoseurxvt(1)terminals looks like this:And an
xterm(1)I started using my window manager’sdmenu(1)launcher looks like this:The important part to remember about
stdin,stdout, andstderris that they are completely unrelated to the graphical display that the terminal emulators offer. If your terminal program needs to write an error tostderr, say viaperror(3), its output might go to the terminal where you started it or to a session error log such as~/.xsession-errors. If you log in viassh(1)and start yourxterm(1)like this:You’ll see it start up and display
hello. (Assuming yourDISPLAYmatches mine.) If you change the command to:You’ll see that the error message about the incorrect font is sent to the terminal where you started
xterm(1)— not to its own graphical interface. (This is a bit funny, because if you changeSHELLto something that doesn’t exist, or attempt to execute something that doesn’t exist, the error message will be printed within the graphical window instead of to the standard error.)A file that is also open in my terminal emulators is
ptmx(4):Opening the
ptmx(4)device gives the terminal emulator thepipeconnections for the PTY master and slave. It is to thesepipes that the terminal emulator software communicates with the clients and the kernel.I can’t do the
ttylayer justice; I strongly recommend reading theptysection from Advanced Programming in the Unix Environment, 2nd edition for full details. The book (and source code include writing your ownptydriver which can be used to implementscript(1)-like functionality or tricking the standard C IO streams into using line-buffering rather than block-buffering when the program doesn’t provide any command line options to control this natively.