Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
Edu Felipe Avatar asked Jan 08 '10 12:01

Edu Felipe


People also ask

What is output redirection in C?

Before the C shell executes a command, it scans the command line for redirection characters. These special notations direct the shell to redirect input and output. You can redirect the standard input and output of a command with the following syntax statements: Item.

What is redirection operation in C?

A redirection operator is a special character that can be used with a command, like a Command Prompt command or DOS command, to either redirect the input to the command or the output from the command.

Which symbol is used for redirecting the output?

The > symbol is known as the output redirection operator. The output of a process can be redirected to a file by typing the command followed by the output redirection operator and file name.

Which operator is used to redirect output of a program?

Regular output append >> operator This allows you to redirect the output from multiple commands to a single file. For example, I could redirect the output of date by using the > operator and then redirect hostname and uname -r to the specifications. txt file by using >> operator.


1 Answers

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

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

$

In the shell you can use test:

$ test -t 1 && echo is a tty
is a tty
$ (test -t 1 && echo is a tty ) |  cat
$
like image 143
William Pursell Avatar answered Sep 19 '22 17:09

William Pursell