Let's take a look at the following example.
A.C:
Copy codeThe Code is as follows: 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:Copy codeThe Code 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 following code:Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: 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,Copy codeThe Code is as follows: "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 ."