代码:
1 #include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <unistd.h> 5 #include <sys/wait.h> 6 7 using namespace std; 8 9 int main(int argc,char* argv[]){ 10 11 pid_t pid; 12 for(int i = 0; i < 1; i++){ 13 cout<<"fork!"; 14 pid = fork(); 15 if(pid == 0){ 16 cout<<"I am child, my pid is "<<getpid()<<endl; 17 }else{ 18 cout<<"I am father, my pid is "<<getpid()<<endl; 19 wait(NULL); 20 } 21 } 22 23 return 0; 24 }
输出:
fork!I am father, my pid is 7499 fork!I am child, my pid is 7500
假如程序第13行改为
cout<<"fork!"<<endl;
则输出变为
fork! I am father, my pid is 7360 I am child, my pid is 7361
分析:
cout先输入到缓冲区(没有直接输出到屏幕),执行fork后缓冲区被复制。加了endl则会直接输出,可以看出endl有换行和清空的作用。
时间: 2024-10-20 08:48:25