C Tutorial: isatty
Identifying whether a file descriptor is associated with a terminal
In general, programs read from the standard input and write to the standard output, oblivious to whether the data is coming from or going out to a file or to the terminal. It is sometiems useful for a program to know whether it is interacting with a user or getting its data from a file.
One common example is when a command interpreter has to issue prompts to the user. In that case, it is useful to know if the input is coming from the terminal or from a file or pipe. Another example is when the output might be formatted differently for a terminal, such as generating multi-column output or printing a header. The ls command is an example of such behavior, where it generates multi-column output on a terminal but single-column output for a file. One may argue that this is bad design since the user does not have direct feedback on what the output would look like when piped to another command or saved to a file.
the
Example
This is a small program that tells you if the standard input and standard output are associated with a terminal.
Save this file by control-clicking or right clicking the download link and then saving it as isatty.c.
Compile this program via:
If you don't have gcc, You may need to substitute the gcc command with cc or another name of your compiler.
Run the program:
You can test it by running:
$ ./isatty
the standard input is from a terminal
the standard input is to a terminal
If you replace the standard input with the null device:
$ ./isatty </dev/null
the standard input is NOT from a terminal
the standard output is to a terminal
If you replace the standard output with a pipe to the cat
command:
$ ./isatty |cat
the standard input is from a terminal
the standard input is NOT to a terminal