i'm sure of my difficulty but not of the reason for it, so my title might not be a good question for this problem :/
i'm creating a function that works as printf, let's call it print2
, and for the sake of testing it i've written this little code that includes redirection of stdout and macro, because i want to see on the standard output the action of the real printf, the action of my print2
, and store those results in two files out1 and out2 (in order to compare them after that). it works fine (see below), but for other reasons i need to change the order of the actions in the macro, and here the problems happens.
what works :
#include "printf2.h"
#include <stdio.h> // for printf
#include <fcntl.h> // for dup() and dup2() and open() and close()
#define PRINT(string) \
printf("printf:" string "\n"); \
print2("print2:" string "\n\n"); \
dup2(out1, 1); \
printf("printf:" string "\n"); \
dup2(out2, 1); \
print2("print2:" string "\n"); \
dup2(save, 1);
int main(void)
{
int out1 = open("out1.txt", O_WRONLY | O_TRUNC);
int out2 = open("out2.txt", O_WRONLY | O_TRUNC);
int save = dup(1);
PRINT("test1");
PRINT("test2");
close(out1);
close(out2);
close(save);
return (0);
}
that gives me this output on the console :
printf:test1
print2:test1
printf:test2
print2:test2
and out1.txt :
printf:test1
printf:test2
and out2.txt :
print2:test1
print2:test2
perfect, i can visually compare on the console, and write a function to compare in the files.
what doesn't works :
But as i said, of course my code is far more complicated and for external reason i need to do that in another order, this one (first write into the files, then on the console) :
#define PRINT(string) \
dup2(out1, 1); \
printf("printf:" string "\n"); \
dup2(out2, 1); \
print2("print2:" string "\n"); \
dup2(save, 1); \
printf("printf:" string "\n"); \
print2("print2:" string "\n\n");
and it gives me messed up things, on the console i've got this :
print2:test1
print2:test2
printf:test1
printf:test1
printf:test2
printf:test2
in file out1.txt :
[empty]
in file out2.txt :
print2:test1
print2:test2
i tried to replace all 'printf()' instance with 'print2()' or with 'write()' and it worked, so it seems to me that printf just take too long to print on the console and the output file descriptor has already been changed... Am i right ? and is there a solution ? a way to wait for printf to end before to continue the program maybe ?
Output to stdout is buffered by the system. The fflush call will force all buffered output to be written. Do fflush(stdout)
to complete all printing before making changes to the streams.