Code:
1#include <iostream>2#include <string>3#include <cstdio>4#include <unistd.h>5#include <sys/wait.h>6 7 using namespacestd;8 9 intMainintargcChar*argv[]) {Ten One pid_t pid; A for(inti =0; I <1; i++){ -cout<<"fork!"; -PID =fork (); the if(PID = =0){ -cout<<"I am Child, my PID is"<<getpid () <<Endl; -}Else{ -cout<<"I am Father, my pid is"<<getpid () <<Endl; + Wait (NULL); - } + } A at return 0; -}
Output:
fork! I am Father, my pid is 7499fork! I am Child, my PID is 7500
If the 13th line of the procedure is replaced
cout<<"fork! "<<endl;
The output becomes
fork! I am Father, my pid is 7360I am child, my PID is 7361
Analysis:
The cout is first entered into the buffer (no direct output to the screen) and the buffer is copied after the fork is executed. Add the Endl will be directly output, you can see Endl has the role of line and empty.
Basic usage of the fork function in Linux