The fork () function of C language is used to create the use of child processes _c language

Source: Internet
Author: User
Tags error handling

Let's take a look at an example of using fork to invoke the EXECLP () function to implement the PS or LS command under Linux:

#include "sys/types.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"

int main ()
{
 pid_t result;
 Result=fork ();
 Error handling
 if (result==-1)
 {
  printf ("Fork error\n");
 }
 Son
 else if (result==0)
 {//Call EXECLP () function, equivalent to "Ps-ef"
 if ((RESULT=EXECLP ("PS", "PS", NULL)) <0);      
    printf ("son\n");
 }
 Father
    Else 
 {
 if (RESULT=EXECLP ("ls", "ls", NULL) <0);  
       printf ("father\n");
 }
 

Generally speaking, we write 1 ordinary C program, run this program until the end of the program, the system will only assign 1 PID to this program, also said, the system will only have a process on the program.
But executing the fork () function is different.
Fork this English word in English is "forked" meaning, fork () This function is also very consistent with this meaning. Its role is to replicate the current process (including the stack data in memory) for 1 new mirrors. The new mirror is then executed simultaneously with the old process. Equivalent to 1 processes, the fork () function is encountered and split into two processes at the same time. And the two processes are not mutually affected.
Refer to this applet below:

int Fork_3 () { 
  printf ("It ' s" main process step 1!! \ n '); 
 
  Fork (); 
 
  printf ("Step2 after Fork" ()!! \ n '); 
 
  int i; scanf ("%d", &i);  Prevent exiting return 
  0; 
} 

In this function, there are two printf statements, but 3 lines of information are played when execution is performed. The following figure:

Why, because the fork () function forked the program, see the following diagram:

You can see that the program has only 1 main processes when the fork () function executes, so step 1 is printed out 1 times.
After the fork () function is executed, the program fork becomes two processes, one is the original main process, the other 1 are new subprocess, they will perform the code behind the fork () function, so Step2 will be printed out by two processes each time, a total of 3 printf statements on the screen!
You can see the last side of this function I used the scanf () function to prevent the program from exiting, when the process of viewing the system, you will find two of the same name of the process:

As shown above, PID 8808 that is the main process, and PID 8809 that is the child process ah, because its parent PID is 8808 Ah!
It should be noted that if no special processing is done, the subprocess will always exist, even if the fork_3 () function is called, and the child process, like the main program, returns the previous level of the call to the Fork_3 () function until the entire program exits.
It can be seen that if the fork_3 () is executed 2 times, the main program will fork two times, and eventually become 4 processes, is not a bit dangerous. So the above so-called special treatment is very important AH!

Distinguish between main programs and subroutines
in practical applications, simply making the program fork is not very meaningful, we add a subroutine, most likely to let the child process to execute a piece of code alone. Implement functions that are different from the main process.
To implement the functionality described above, the child process and the main process are actually executing different code.
So fork () actually has the return value, and the return value in the two process is different, and in the main process the fork () function returns the PID of the main process and returns 0 in the child process! So we can judge the process by the return value of fork (), we can use if statement to execute different code!
As the following applet Fork_1 ():

int Fork_1 () { 
  int childpid; 
  int i; 
 
  if (fork () = = 0) { 
    //child process for 
    (i=1. i<=8; i++) { 
      printf ("This is Child process\n"); 
    } 
  else{ 
    //parent process for 
    (i=1. i<=8; i++) { 
      printf ("This is parent process\n"); 
    } 
 
  printf ("Step2 after Fork" ()!! \ n \ nthe "); 
} 

I've judged the return value of the fork () function, and if the return value is 0, I'll let it be a subprocess, or it's the main program. Then I can let the two processes output different information.
The output information is shown below:

You can see the subroutine and the main program output 8 different information, but they are not the alternate rule output, because their two processes are parallel to each other, whose hands on the screen first output, each run results may be different oh.
Here is the diagram:

All two processes are judged by the fork () return value, and the respective code is executed separately in the IF judgment statement. But if the judgment is complete, the following code will be executed back to the individual. So the Step2 still output 2 times.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.