看了这篇关于 C 语言里,main 函数中 return x 和 exit(x) 到底有什么区别 ? 的集合版的文章,能大概知道之所以然,但还是觉不太通俗易懂,自己从床上爬起来,敲了一下代码,并用自己理解的方式在代码旁边加了注释,如下:
#include <iostream>
#include <sys/wait.h>
#include <unistd.h> //fork()
#include <stdlib.h> //exit()
using namespace std;
int democ(){
cout<<"child inside return"<<endl;
exit(0);
return 10;
}
int demop(){
cout<<"parent inside return"<<endl;
return 11;
}
int main(int argc, char *argv[])
{
int pid = fork();
// int pid = vfork();
if (pid < 0)
{
exit(1);
}
else if(pid ==0){
cout<<democ()<<endl;
exit(0); //just like break in chile process,acturally,vfork is borned to multi process;usually in mutil process ,application needs to be stop in one child but don't affect the parent process at the same time,so exit() is for this case,in another word,exit only works for one process at a time. cout<<"child outside return"<<endl;
cout<<"it won't run to here in child with exit() working before"<<endl;
// return 0; //for vfork, child process and parent process share resouces:like page,stack,so this return's target is the share main(); but for fork,using copy on write, child procecss use one copy recoues of prarent process,so the target of this return is child's main(),it won't affect prarent's process
}
else{
wait(NULL);
cout<<demop()<<endl;
cout<<"parent outside return"<<endl;
return 0;
}
}