Determining if STDERR is going to the terminal

I have a set of Java programs that are used as command line tools on our Linux servers. Most of them use a class that prints a progress bar on STDERR, similar to Perl Term::ProgressBar.

I would like the progress bar to be shown whenever STDERR is sent to the terminal and automatically shuts down when STDERR is redirected so that not all kinds of progress indicators are in redirected data.

Checking System.console() == nullwas my first thought, but redirecting STDOUT is enough to do this true, even if STDERR still goes to the terminal. Is there anything I can verify that is typical of STDERR? A Linux-specific solution or using native APIs would be ok for my needs.

+5
source share
2 answers

I think you are looking isatty(3)at unistd.h. It is not possible to determine if the file descriptor has been redirected to a period, but this will tell you if it is still interactive. See Command Source ttyin GNU coreutils.

+1
source

@chrylis pointer , , , :

  • Java-
  • javah C.
  • .cpp , isatty
  • ++
  • Java, -Djava.library.path=..., ,

Java:

package com.example.cli;

class LinuxTerminalSupport {

    public native boolean isStderrVisible();

    static {
        System.loadLibrary("term");
    }
}

ant target .h:

<target name="generate-native-headers">
    <javah destdir="native/" verbose="yes">
        <classpath refid="compile.class.path"/>
        <class name="com.example.cli.LinuxTerminalSupport" />
    </javah>
</target>

.cpp :

#include "com_example_cli_LinuxTerminalSupport.h"
#include "unistd.h"

using namespace std;

JNIEXPORT jboolean JNICALL Java_com_example_cli_LinuxTerminalSupport_isStderrVisible(JNIEnv * env, jobject obj) {
    return isatty(fileno(stderr)) == 1;
}

Makefile ( java $JAVA_HOME):

linux: LinuxTerminalSupport.o
    g++ -I/usr/java/jdk1.6.0_13/include -I/usr/java/jdk1.6.0_13/include/linux \
            -o libterm.so -shared -Wl,-soname,term.so LinuxTerminalSupport.o -lc

LinuxTerminalSupport.o: LinuxTerminalSupport.cpp
    g++ -c -I/usr/java/jdk1.6.0_13/include -I/usr/java/jdk1.6.0_13/include/linux LinuxTerminalSupport.cpp
0

All Articles