Parsing C stdout and stderr some details easy to overlook _c language

Source: Internet
Author: User
Tags strlen
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. "

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.