fork:
fork函数调用一次,返回两次;对于子进程,返回值0; 对于父进程,返回的是子进程的进程ID。
#include<iostream>
#include<string.h>
#include<sys/unistd.h>
#include<syscall.h>
#include<pthread.h>
using namespace std;
int main(){
cout<<"TID = "<<syscall(SYS_getpid)<<" pid = "<<getpid()<<" aa"<<endl;
if(fork()){
cout<<"TID = "<<syscall(SYS_getpid)<<" pid = "<<getpid()<<" bb"<<endl;
}
cout<<"TID = "<<syscall(SYS_getpid)<<" pid = "<<getpid()<<" ee"<<endl;
return 0;
}
TID = 37723 pid = 37723 aa 父进程
TID = 37723 pid = 37723 bb 父进程
TID = 37723 pid = 37723 ee 父进程
TID = 37727 pid = 37727 ee 子进程
从if条件中的fork()开始,父进程37723创建子进程
#include<iostream>
#include<string.h>
#include<sys/unistd.h>
#include<syscall.h>
#include<pthread.h>
using namespace std;
int main(){
cout<<"TID = "<<syscall(SYS_getpid)<<" pid = "<<getpid()<<" aa"<<endl;
if(fork()){
cout<<"TID = "<<syscall(SYS_getpid)<<" pid = "<<getpid()<<" bb"<<endl;
}
auto childid = fork();
if(childid<0){cout<<"fork failed"<<endl;exit(1);}
if(childid>0){cout<<" 父进程 "<<"TID = "<<syscall(SYS_getpid)<<" chidid= "<<childid<<" pid = "<<getpid()<<" cc"<<std::endl;}
if(childid==0){cout<<" 子进程 "<<"TID = "<<syscall(SYS_getpid)<<" chidid= "<<childid<<" pid = "<<getpid()<<" dd"<<std::endl;}
cout<<"TID = "<<syscall(SYS_getpid)<<" pid = "<<getpid()<<" ee"<<endl;
return 0;
}
上面的代码一共创建了4个进程:
1父进程
2 if条件创建的第一个儿子进程
3 后面auto childid = fork(),儿子进程也创建了孙子进程
4 同时auto childid = fork() 父进程也创建了另一个儿子进程
打印结果:
父进程:37948:aa bb cc ee
第一个儿子进程:37957 :cc ee
这个儿子进程得到的孙子进程id: 37959: dd ee
父进程创建的第二个儿子进程:37958: dd ee