A detailed description of the fork () function in Linux

Source: Internet
Author: User

Required header Files :

#include <sys/types.h>

#include <unistd.h>


pid_t fork (void)

features :

Used to create a new process from an existing process called a child process, the original process is called the parent process.

Parameters :

No

return value :

Success: 0 is returned in the child process, and the child process ID is returned in the parent process. pid_t, as an unsigned integer.

Failed: returned-1.

The two main reasons for failure are:

1) The current number of processes has reached the system-specified limit, when the value of errno is set to Eagain.

2) system memory is low, then the value of errno is set to Enomem.


The test examples are as follows:

#include <stdio.h> #include <unistd.h> #include <sys/types.h>int main (int argc, char *argv[]) {fork (); printf ("id = =%d\n", Getpid ());//Get process number return 0;}


The results of the operation are as follows:



From the result of the operation, we can see that the print function after fork () has been printed two times, and two process numbers have been printed, which shows that fork () does create a new process, the new process is a child process, and the original process is the parent process.


What does the child process look like?

the child process that is obtained by using the fork () function is a replica of the parent process that inherits the address space of the entire process from the parent process: including the process context (static description of the process execution activity), the process stack, open file descriptor, signal control settings, process priority, process group number, and so on. The child process is unique only to its process number, timer, etc. (only a small amount of information). Therefore, the cost of using the fork () function is very large.

simply put, after a process calls the fork () function, the system first assigns resources to the new process, such as space for storing data and code. All the values of the original process are then copied to the new new process, with only a few values that are different from the value of the original process. The equivalent of cloning a self.


in fact, to be more accurate , the fork () use of Linux is achieved through a write-time copy (Copy-on-write). Write-time copying is a technique that can postpone or even avoid copying data. The kernel does not replicate the entire process's address space at this time, but instead lets the parent-child process share the same address space. The address space is copied only when it needs to be written, allowing each to have its own address space. That is, the replication of a resource is done only when it is required to be written, before which it is shared only in read-only mode.


A child process is a replica of the parent process and can be simply thought of as a parent-child process code. That people think of no, so, what the parent process does, what the sub-process also do (such as the above example), is not able to meet our requirements to achieve multi-tasking, then we have to think of a way to distinguish between the father and son process, this through the fork () return value.


The fork () function is called once, but returns two times. The difference between two returns is that the return value of the child process is 0, and the return value of the parent process is the process ID of the new child process.


The test examples are as follows:

#include <stdio.h> #include <unistd.h> #include <sys/types.h>int main (int argc, char *argv[]) {pid_t Pid;pid = fork (), if (PID < 0) {//not created successfully perror ("fork");} if (0 = = pid) {//Sub-process while (1) {printf ("I am son\n"); sleep (1);}} else if (PID > 0) {//parent process while (1) {printf ("I am father\n"); sleep (1);}} return 0;}

The results of the operation are as follows:



By running the results, you can see that the parent-child process does one thing (print a single sentence). Here, we just see that there is only one piece of code, in fact,after fork (), there are two address spaces running independently , somewhat like two separate programs (parent-child processes) running. It is important to note that in the child process's address space, the child process starts executing the code from the fork () function .


In general, it is indeterminate whether the parent process executes first or the child process after the fork (). This depends on the scheduling algorithm used by the kernel.


In the following example, the individual address spaces of the parent-child process are verified as separate:

#include <stdio.h> #include <unistd.h> #include <sys/types.h>int a = 10;//global variable int main (int argc, char *a Rgv[]) {int b = 20;//local variable pid_t pid;pid = fork (), if (PID < 0) {//not created successfully perror ("fork");} if (0 = = pid) {//Sub-process a = 111;b = 222;//Child process modifies its value printf ("son:a =%d, B =%d\n", A, b);} else if (PID > 0) {//Parent process sleep (1);//Ensure that the child process runs printf first ("father:a =%d, B =%d\n", A, b);} return 0;}

The results of the operation are as follows:



By knowing that the value of the variable, A and B is modified in the child process, the value of the parent process, A, B is not affected.


In the future programming, fork () is best to add judgment, which is the space of the child process, which is the space of the parent process, otherwise, fork () after the code for the parent-child process has a copy, for the user, there is no significant, such as Example 1.


Sample code download please click here.

A detailed description of the fork () function in Linux

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.