Fork and printf buffering issues

Source: Internet
Author: User
Tags glob

printf Output conditions:

(1) Call fflush;

(2) the buffer is full;

(3) encountered \ r \ n These characters

(4) Encounter scanf these to take the buffer;

(5) The thread or process exits;

The buffer of the parent process is copied after the fork;

Code:

1#include <unistd.h>2#include <stdio.h>3 4 5 intGlob =6;6 CharBuf[] ="a write to stdout\n";7 8 intMain ()9 {Ten     int var; One pid_t pid; A  -     var= the; -  the     if(Write (Stdout_fileno, buf,sizeof(BUF)-1) !=sizeof(BUF)-1){ -Perror ("Write error\n"); -         return-1; -     } +  -printf"before fork\n"); +  A     if(PID = fork ()) <0){ atPerror ("Fork error\n"); -         return-1; -}Else if(PID = =0){ -glob++; -         var++; -}Else { inSleep (2); -     } to  +printf"pid =%d, Glob =%d, var =%d\n", Getpid (), Glob,var); -  the     return 0; *}

Results:

[Email protected] forkprintf]#GCCFORKPRINTF.C-o forkprintf[[email protected] forkprintf]#./FORKPRINTFAWriteTo Stdoutbefore forkpid=17098, Glob =7, var = thePID=17097, Glob =6, var = the[email protected] forkprintf]#./forkprintf >Tmp.out[[email protected] forkprintf]#CatTmp.outaWriteTo Stdoutbefore forkpid=17106, Glob =7, var = thebefore Forkpid=17105, Glob =6, var = the

(1) For the first time input to the console, write unbuffered direct output, printf ("before fork\n") there is a \ n line buffer identity direct output, and the child process copies the parent process code snippet, and then output the last printf;

(2) The second input to the file, write unbuffered direct output, printf ("before fork\n") into a fully buffered and no output, the child process copies the parent process buffer and code snippet, so when the parent-child process exits, flush buffer, there are two printf output;

Fork and printf buffering issues

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.