One thing you will need to do before this works at all is to call fflush(stdout); before switching the file descriptor stdout from under it. What is likely to happen is that the standard C library buffers your output without suspecting that you are moving around the file descriptors below it. The data you write with printf() is not actually sent to the base file descriptor until its buffer is full (or your program returns with main ).
Insert the call as follows:
fflush(stdout); if(dup2(file, 1) < 0) {
before both calls to dup2() .
source share