I’ve been programming (in C) in Unix for a few months, and it occurred to me that nothing I’ve learned so far allows me to write a program that emulates a small part of the functionality of the basic program ‘more’ that lives on every Unix workstation.
Specifically, I don’t know how to handle input and output like more does. If you’re reading this, you probably know that the purpose of more is to display the contents of a text file in a convenient way. There are various ways to call more from a shell. When invoked as
more < sometextfile
or
someothercommand | more
more will, as one would expect, display the contents of sometextfile or the output of someothercommand in a convenient way. However, unlike the programs I know how to write, more still accepts commands interactively from the keyboard, even in such cases, where its “standard input” is supposedly redirected.
On the other hand,
more sometextfile
has the exact same effect as
more < sometextfile.
Remarkably, more does not read lines of input from the keyboard and display them. However, it does accept commands interactively from the keyboard in the exact same way as it does when its input is redirected. In this way, the way more uses its “standard input” is fundamentally different depending on whether the shell has redirected its standard input or not.
Moreover,
more sometextfile | someothercommand
is fundamentally different from the above cases: in this case, more does not use keyboard input at all.
The thing that is simply beyond me right now is that the program more is able to respond differently based on where the shell connects its input and output; I don’t even know how to tell, from within a process, whether the process’s input/output have been redirected by the shell. And secondly, no matter where the shell connects the input of more, more retains the ability to accept commands directly from the keyboard.
So how can a program tell where its standard input is coming from and where its standard output is going? And how can a program take commands directly from the keyboard if the shell has redirected its standard input? If anything isn’t clear, I’d be happy to clarify.
(P.S.: Thanks to those who responded to my previous GQ’s, A Proof of the Riemann Hypothesis?, and General Animalian Color Vision.)