Difference between return and exit functions: returnexit Function
In Linux, the teacher mentioned that the subprocess generated by calling vfork is to use the exec family function to execute other code logic.
When a sub-process exits, there are two methods: exit and exec functions. return is not allowed. Why not return is used? Why does vfork not allow return?
So I wrote this code.
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<stdlib.h> 4 5 6 int main() 7 { 8 pid_t pid; 9 pid=vfork(); 10 if(pid==0) 11 { 12 //child 13 printf("I am child pid:%d\n",getpid()); 14 ···· 15 return 0;16 } 17 else 18 { 19 //father 20 printf("I am father pid:%d\n",getpid()); 21 } 22 return 0; 23 }
Unexpected error
In addition, the error results may be different depending on the operating system version. Some systems may have endless loops, and the two sentences shown in the figure above may be output repeatedly.
So why? The return and exit functions can end a process. Why is there such a big gap between the results? And why is the fork okay?
First, look for the differences between them,The biggest difference between fork and vfork is, of course, the address space of the Parent and Child processes.,The child process generated by vfork shares the same address space with the parent process.That is to say, from the bottom of the address space to the top is all common. One is changed, and the other is modified.
Then let's look at return and exit. in simple words, they are all used for exit. They refresh the buffer and then exit,But! From the literal meaning, we can see that return has the meaning of returning. My previous blog talked about the Function stack frame construction method. When the function returns the function called at the upper level, the pointer in the stack frame will be moved, and the meaning of "return" is here !!! Returns the function called at the upper level, and modifies the stack frame pointer to returnThen, let's look at the sub-process and parent process generated by vfork, which share the address space, so the stack is also included ~,Once the sub-process uses return, it will rewrite the stack (the function stack frame, especially the main! Simply put, the child process pulls the parent process along the way when the main process is killed. The parent process means that it will die if nothing is known...At this time, the system will report a segment error, but some operating systems will let the parent process return to main for re-execution, so it will be an endless loop...
Please criticize and correct me...