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

后端 未结 3 2110
悲哀的现实
悲哀的现实 2020-12-10 04:18

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 04:58

    Have a look at this code:

    int is_redirected(){
       if (!isatty(fileno(stdout))){
           fprintf(stdout, "argv, argc, someone is redirecting me elsewhere...\n");
           return 1;
       }
       return 0;
    }
    
    /* ... */
    int main(int argc, char **argv){
        if (is_redirected()) exit(-1);
        /* ... */
    }
    

    That function will return 1 if the program is being redirected. Notice in the main(...) how it is called. If the program was to run and is being redirected to stderr or to a file the program exits immediately.

提交回复
热议问题