Let's take a look at the following example.
A.C:
Int main (INT argc, char * argv []) {fprintf (stdout, "normal \ n"); fprintf (stderr, "Bad \ n"); Return 0 ;}
$./
Normal
Bad
$./A> TMP 2> & 1
$ Cat TMP
Bad
TMP
We can see that, after redirecting to a file, bad is before normal.
The reason is as follows:
"The stream stderr is unbuffered. The stream stdout is line-buffered when it points to
Terminal. Partial lines will not appear until fflush (3) or exit (3) is called, or a newline
Is printed. This can produce unexpected results, especially with debugging output.
Buffering mode of the standard streams (or any other stream) can be changed using
Setbuf (3) or setvbuf (3) call ."
Therefore, you can use the followingCode:
Int main (INT argc, char * argv []) {fprintf (stdout, "normal \ n"); fflush (stdout); fprintf (stderr, "Bad \ n "); return 0 ;}
In this way, it will be normal to redirect to a file. however, this method only applies to a small amount of output. The global setting method also needs to use setbuf () or setvbuf (), or use the following system call:
Int main (INT argc, char * argv []) {write (1, "normal \ n", strlen ("normal \ n"); write (2, "Bad \ n", strlen ("Bad \ n"); Return 0 ;}
But try not to use both the file stream and file descriptor,
"Note that mixing use of files and raw file descriptors can produce unexpected results and
Shoshould generally be avoided. A general rule is that file
Descriptors are handled in the kernel, while stdio is just a library. This means for exam-
Ple, that after an exec (), the child inherits all open file descriptors, but all old
Streams have become inaccessible ."