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 isatty library function takes a file descriptor as a parameter and returns 1 if that file descriptor is associated with a terminal. Otherwise it returns 0.

Example

This is a small program that tells you if the standard input and standard output are associated with a terminal.

/* isatty demo */ /* Paul Krzyzanowski */ #include <stdlib.h> /* needed for exit() */ #include <unistd.h> /* needed for isatty() */ #include <stdio.h> /* needed for printf() */ int main(int argc, char **argv) { if (isatty(0)) printf("the standard input is from a terminal\n"); else printf("the standard input is NOT from a terminal\n"); if (isatty(1)) printf("the standard output is to a terminal\n"); else printf("the standard input is NOT to a terminal\n"); exit(0); }

Download this file

Save this file by control-clicking or right clicking the download link and then saving it as isatty.c.

Compile this program via:

gcc -o isatty isatty.c

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:

./isatty

You can test it by running:


$ ./isatty
the standard input is from a terminal
the standard input is NOT 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

Recommended

The Practice of Programming

 

The C Programming Language

 

The UNIX Programming Environment