Linux fork function

Source: Internet
Author: User

The bifurcation function in computer programming. Return value: If the call is successful, two values are returned, the child process returns 0, and the parent process returns the child process token; otherwise, an error returns-1. The fork function divides the running program into 2 (almost) identical processes, each of which initiates a thread that executes from the same location in the code. The threads in both processes continue to execute, as if two users had started two copies of the application at the same time. Here is an example of how the fork function works.

#include <unistd.h>  #include <stdio.h>   int main ()   {       pid_t fpid;//fork returns fpid     int cnt=0;      Fpid=fork ();       if (Fpid < 0)           printf ("Error in fork!");       else if (Fpid = = 0) {          printf ("I am the child process,  process ID:%d\n", Getpid ());           cnt++;      }      else {          printf ("I am the parent process,  process ID:%d\n", Getpid ());           cnt++;      }      printf ("Count:%d\n", CNT);      return 0;  }  
Run GCC Fork.c-o fork to get the fork executable file, run:./fork

The following results are obtained:

I am The parent process, process  id:1924count:1i am the child process,  process id:1925count:1
After the fpid=fork () statement, two processes execute code starting with if (fpid<0). Because the stack segment of the parent process is copied at copy time, two processes are stuck in the fork function, waiting to be returned. So the fork function returns two times, once in the parent process, and the other in the child process, and the return value of the two times is different.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux fork function

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.