How can a Unix program display output on screen even when stdout and stderr are redirected?

后端 未结 3 1597
半阙折子戏
半阙折子戏 2021-01-07 21:51

I was running a program (valgrind, actually) on my Ubuntu machine, and had redirected both stdout and stderr to different files. I was surprised to see a short message appea

3条回答
  •  执笔经年
    2021-01-07 22:15

    Here is some sample code that does exactly what was asked (thanks to earlier answers pointing me in the right direction). Both are compiled with g++, and will print a message to the screen even when stdout and stderr are redirected.

    For Linux (Ubuntu 14):

    #include 
    #include 
    #include 
    #include 
    
    int main( int, char *[]) {
    
        printf("This goes to stdout\n");
    
        fprintf(stderr, "This goes to stderr\n");
    
        int ttyfd = open("/dev/tty", O_RDWR);
        const char *msg = "This goes to screen\n";
        write(ttyfd, msg, strlen(msg));
    }
    

    For Windows 7, using MinGW:

    #include 
    #include 
    #include 
    #include 
    
    void writeConsole( const char *s) {
        while( *s) {
            putch(*(s++));
        }
    }
    
    int main( int, char *[]) {  
        printf("This goes to stdout\n");
    
        fprintf(stderr, "This goes to stderr\n");
    
        writeConsole( "This goes to screen\n");
    }
    

提交回复
热议问题