Redirect stdout and stderr to the same file and restore it

前端 未结 1 1186
梦毁少年i
梦毁少年i 2020-12-31 04:16

I am redirecting the output of stderr and stdout of my c program to two files and then restoring the original stdout and stderr:

int sout = dup(fileno(stdout         


        
1条回答
  •  醉梦人生
    2020-12-31 04:25

    Instead of opening the file again for stderr,as in:

    freopen("test.txt","a",stderr);
    

    redirect it to stdout at the file descriptor level by doing:

    dup2(fileno(stdout), fileno(stderr));
    

    Note that stdout and stderr will still use independent user level buffers and, when not directed at an interactive terminal, flushing rules are different. This will most likely be the main cause for different output ordering when redirected. See this explanation of flushing modes and the man page for setvbuf().

    0 讨论(0)
提交回复
热议问题