Parse some details that stdout and stderr are easy to ignore in c

Source: Internet
Author: User

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 ."

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.