This is a follow-up to How to capture output of printf? - specifically the answer by jxh.
I am having the same trouble with the code in the answer that Viesturs was having in 2018. It was suggested to him that he open a new question, which he said his account didn't allow, so I'm opening a new question along the same lines.
On that answer, in 2012, the original questioner said it worked. In 2018, Viesturs said after the code was ran, further output neither appeared on the console nor in the redirected file.
I'm having the same problem. Using the code below, this shouldn't be redirected\n
isn't shown on the console, and isn't in the redirected file. The redirected file only contains the first printed line.
I'm using gcc 8.3.0, and also tried gcc 6.5.0. glibc 2.29.
Note that I do NOT want to freopen
with "CON"
afterward. Even if that works, I want to preserve the original stdout, since it could itself be a redirect. (Although in my testing, it's just been the console.)
Either: the jxh answer has a bug in it; I'm making the same mistake Viesturs was; or (my best guess) there was a bug introduced (or fixed) sometime earlier than gcc 6.5.0 or glibc 2.29.
redirected.c
#include <unistd.h>
#include <stdio.h>
void funcB() {
printf("this should be redirected\n");
fflush(stdout);
}
int main() {
int stdout_fd = dup(STDOUT_FILENO);
freopen("/tmp/redirected", "w", stdout);
funcB();
fclose(stdout);
dup2(stdout_fd, STDOUT_FILENO);
stdout = fdopen(STDOUT_FILENO, "w");
close(stdout_fd);
printf("this shouldn't be redirected\n");
fflush(stdout); // shouldn't make a difference if this is here
}
Output:
$ gcc redirected.c
$ ./a.out
<THERE IS NO OUTPUT>
$ cat /tmp/redirected
this should be redirected