let's look at one of the following examples
A.C:
Copy Code code as follows:
int main (int argc, char *argv[])
{
fprintf (stdout, "normal\n");
fprintf (stderr, "bad\n");
return 0;
}
$/A
Normal
Bad
$/a > TMP 2>&1
$ cat TMP
Bad
Tmp
We see that after redirecting to a file, bad to the front of normal.
The reasons are as follows:
Copy Code code as follows:
"The stream stderr is unbuffered. The stream stdout is line-buffered as it points to a
Terminal. Partial lines won't appear until fflush (3) or exit (3) is called, or a newline
is printed. This can produce unexpected results and especially with debugging output. The
Buffering mode of the standard streams (or any other stream) can is changed using the
SETBUF (3) or SETVBUF (3) call. "
Therefore, you can use the following code:
Copy Code code as follows:
int main (int argc, char *argv[])
{
fprintf (stdout, "normal\n");
Fflush (stdout);
fprintf (stderr, "bad\n");
return 0;
}
This is normal when redirected to a file. However, this method is only suitable for a small amount of output, the global setting method also needs to use SETBUF () or setvbuf (), or use the following system call:
Copy Code code 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 file streams and file descriptors.
Copy Code code as follows:
"Note this mixing use of FILEs and raw file descriptors can produce unexpected results and
Should generally be avoided. A general rule was that file
Descriptors are handled the kernel, while stdio is just a library. This is means for exam-
PLE, which is exec (), the child inherits all open file descriptors, but all old
Streams have become inaccessible. "