Determine whether process output is being redirected in C/C++

Tags: c shell stdout

I'm writing command line utility for Linux. If the output (stdout) is going to a shell it would be nice to print some escapes to colorize output. But if the output is being redirected those bash escapes shouldn't be print, or the content might break parsers that rely on that output.

There are several programs that do this (suck as ack) but the ones I found were written in Perl and I couldn't find out how they did it.

I wanted to use C/C++ to write my utility.


In (non-standard) C, you can use isatty(). In perl, it is done with the -t operator:

$ perl -E 'say -t STDOUT'
$ perl -E 'say -t STDOUT' | cat


In the shell you can use test:

$ test -t 1 

This video can help you solving your question :)
By: admin