父进程和子进程的生成
pid< 0 出错
pid==0 子进程
pid>0 父进程
#include<stdio.h>
#include<unistd.h>
#include<iostream>
using namespace std;
int main()
{
pid_t pid;
char *massage;
pid = fork();
if(pid<0)
{
cout<<"error"<<endl;
}
else if(pid ==0)
{
cout<<"This is a sonpid"<<endl;
cout<<"sonpid=="<<getpid()<<endl;
cout<<"fatherpid=="<<getppid()<<endl;
}
else
{
cout<<"This is a fatherpid"<<endl;
cout<<"pid=="<<getpid()<<endl;
}
for(int i =0;i<4;i++)
{
cout<<getpid()<<endl;
cout<<i<<endl;
}
return 0;
}
循环产生兄弟子进程;
#include<stdio.h>
#include<unistd.h>
#include<iostream>
using namespace std;
int main()
{
pid_t pid;
int number = 5;
int i =0;
for( i =0;i<number;i++)
{
pid = fork();
if(pid ==0)
{
cout<<getpid()<<endl;
break;
}
}
if(i==0)
{
cout<<getpid()<<endl;
}
return 0;
}