How are long command lines ( > $COLUMNS ) automatically wrapped to a new line?

There are several points where I/O is passed through, some of which (to my knowledge) are the shell, pty, tty, termios, terminal emulator application. In most terminal emulators, long command lines (ones that exceed current $COLUMNS) are wrapped to a new line before the user submits the command by pressing Enter. Also, the line is wrapped backward to the line above when the appropriate number of characters are removed from the command line as one would expect.

How does a Linux terminal work?

If you fire up a terminal and call an executable (assuming one that’s line oriented for simplicity) you get a reply to the command from the executable. How does this get printed to you (the user)? Does the terminal do something like pexpect? (poll waiting for output) or what? How does it get notified of output to be printed out? And how does a terminal start a program? (Is it something akin to python’s os.fork()? ) I’m puzzled how a terminal works, I’ve been playing with some terminal emulator and I still don’t get how all this magic works. I’m looking at the source of konsole (kde) and yakuake (possibly uses konsole) an I can’t get where all that magic happens.