代码:
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <sys/wait.h> using namespace std; int main(int argc,char* argv[]){ pid_t pid;
for(int i = ; i < ; i++){
cout<<"fork!";
pid = fork();
if(pid == ){
cout<<"I am child, my pid is "<<getpid()<<endl;
}else{
cout<<"I am father, my pid is "<<getpid()<<endl;
wait(NULL);
}
} return ;
}
输出:
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有换行和清空的作用。