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