How to tell if stderr is directing output to a file? How to tell if stderr is directing output to a file? unix unix

How to tell if stderr is directing output to a file?


Try using isatty() on the file descriptor:

The isatty() function determines if the file descriptor fd refers to a valid terminal type device.

The function fileno() examines the argument stream and returns its integer descriptor.

Note that stderr is always on file descriptor 2, so you don't really need fileno() in this exact case.


Yes, you can use isatty(3) to tell if a file descriptor refers to the terminal or to something else (file, pipe, etc.). File descriptor 0 is stdin, 1 is stdout, and 2 is stderr.

if(isatty(2))    // stderr is a terminal