I want to be able to output to both stdout(&stderr) AND to another file (log file) without worrying that the log file would get corrupted output for the case when shell is redirecting stdout(and/or stderr) to the same log file.
For my particular case, I've tried checking the stat bits(man 2 stat) for stdout and for the log file, in order to determine that they point to the same device and inode, in which case don't fopen() the log file but instead fopen() the stdout file, for writing to the log file.
Exactly what I mean(.c code): https://github.com/libcheck/check/issues/188#issuecomment-492852881
This works as a workaround.
Here's a .c code example:
#include <stdio.h>
int main() {
FILE *f=NULL;
f = fopen("/tmp/a_out_.log", "w");
if (NULL == f) {
fprintf(stderr,"oopsie\n");
} else {
fprintf(stdout, "Something");
fprintf(f," messy ");
fprintf(f," jessy\n");
fprintf(stdout, " or another\n");
fprintf(f,"More stuff\n");
fclose(f);
}
}
Run like this(from bash) to see the overwritten output:
$ gcc a.c && { ./a.out >/tmp/a_out_.log ; cat /tmp/a_out_.log ; }
Something or another
uff
I've simplified the .c code and reduced it to a bash lines, but the functionality (ie. garbled output) is illustrated just the same:
All of these show correct output:
(echo "1 2 3 4 5 6 7 8 9 10" ; echo "blah" >&2)
(echo "1 2 3 4 5 6 7 8 9 10" ; echo "blah" >&2) 1>/tmp/good 2>&1 ; cat /tmp/good
(echo "1 2 3 4 5 6 7 8 9 10" ; echo "blah" >&2) 1>/dev/stdout 2>/dev/stdout
(echo "1 2 3 4 5 6 7 8 9 10" ; echo "blah" >&2) 1>/proc/self/fd/1 2>/proc/self/fd/1
(echo "1 2 3 4 5 6 7 8 9 10" ; echo "blah" >&2) 1>/proc/self/fd/2 2>/proc/self/fd/2
output is:
1 2 3 4 5 6 7 8 9 10
blah
But, the following one shows overwritten output:
(echo "1 2 3 4 5 6 7 8 9 10" ; echo "blah" >&2) 1>/tmp/bad 2>/tmp/bad; cat /tmp/bad
(the corrupted)output looks like:
blah
4 5 6 7 8 9 10
Real world example of where this is happening(with reproduction steps even): https://github.com/libcheck/check/issues/188
filewithterminal(in what you said) and for that it works, why? Real problem? use same log file for this case github.com/libcheck/check/issues/188