fork function and vfork function

fork function

In many applications, creating multiple processes is an effective method for task decomposition. For example, a network server process can create a new subprocess to process each request while listening for client requests. At the same time, the server process will continue to listen for more client connection requests. Decomposing tasks in such a way usually simplifies the design of applications and improves the concurrency of the system. (that is, more tasks or requests can be processed at the same time. )

1 #include <sys/types.h>     
2 #include <unistd.h>    
3 pid_t fork(void); //Return: 0 in child process and child in parent process I D,The error is-1  

There will be two processes after the call is executed, and each process continues from the return of fork().

The two processes will execute the same program text segment, but each has different stack segment, data segment and heap segment copies. At the beginning of the stack, data and stack segment of the child process, the corresponding parts of the memory of the parent process are completely copied. After fork(), each process can modify its own stack data and variables in the heap segment without affecting the other process.

Note: many current implementations do not make a full copy of the parent process's data segments and heap, because exec is often followed by fork. As an alternative, copy on write (cow) technology is used. These areas are shared by the parent and child processes, and the kernel changes their access permissions to read-only. (see Linux UNIX system programming manual for details)

The program code can distinguish the parent and child processes by the return value of fork(). In the parent process, fork () returns the process ID of the newly created child process.

When a child process cannot be created, fork() returns - 1. The reason for the failure may be that the number of processes either exceeds the limit (rlimit? Nproc) imposed by the system on the number of processes for this real user ID, or reaches the system level limit of the maximum number of processes allowed to be created by the system.

Generally speaking, it is uncertain whether the parent process executes first or the child process executes first after the fork. This depends on the scheduling algorithm used by the kernel. If the parent and child processes are required to synchronize with each other, some form of interprocess communication is required.

example:

 1 #include<stdio.h>
 2 #include<sys/types.h>
 3 #include<unistd.h>
 4 #include<sys/wait.h>
 5 #include<stdlib.h>
 6 #include<errno.h>
 7 #include<string.h>
 8 
 9 int main()
10 {
11     pid_t childPid;
12     /* if((childPid=fork())==-1)
13     {
14         printf("Fork error %s\n",strerror(errno));
15         exit(1);
16     }
17     else
18         if(childPid==0)
19         {
20             printf("I am the child : %d\n",getpid());
21             exit(0);
22         }
23         else
24         {
25             printf("I am the father : %d\n",getpid());
26             exit(0);
27         } */
28         switch(childPid=fork()){
29             case -1:
30                 printf("Fork error %s\n",strerror(errno));
31                 exit(1);
32             case 0:
33                 printf("I am the child : %d\n",getpid());
34                 exit(0);
35             default:
36                 printf("I am the father : %d\n",getpid());
37                 exit(0);
38                 
39         }
40     return 0;
41 }

result:

 

vfork function

Similar to fork(), vfork() creates a new subprocess for the calling process. However, vfork() is specifically designed for subprocesses to execute exec() programs immediately.

#include <sys/types.h>     
#include <unistd.h>    
pid_t vfork(void); //Return: 0 in child process, child in parent process I D,The error is-1  

vfork() creates a child process just like fork(), but it does not copy the address space of the parent process to the child process completely, because the child process will immediately call exec (or exit), so the address space will not be accessed. However, before a child process calls exec or exit, it runs in the space of the parent process. Another difference between vfork() and fork() is that vfork() ensures that the child process runs first, and that the parent process may not be scheduled until it calls exec or exit. (if the child process depends on further actions of the parent process before these two functions are called, a deadlock can result.)

example:

 1 #include<stdio.h>
 2 #include<sys/types.h>
 3 #include<unistd.h>
 4 #include<sys/wait.h>
 5 #include<stdlib.h>
 6 #include<errno.h>
 7 #include<string.h>
 8 
 9 int main()
10 {
11     pid_t childPid;
12     if((childPid=vfork())==-1)
13     {
14         printf("Fork error %s\n",strerror(errno));
15         exit(1);
16     }
17     else
18         if(childPid==0)         //Subprocess
19         {
20             sleep(1);           //Subprocess sleep for one second
21             printf("I am the child : %d\n",getpid());
22             exit(0);
23         }
24         else                      //Parent process
25         {
26             printf("I am the father : %d\n",getpid());
27             exit(0);
28         }
29     /* switch(childPid=vfork()){
30             case -1:
31                 printf("Fork error %s\n",strerror(errno));
32                 exit(1);
33             case 0:               //Subprocess
34                 sleep(1);        //Subprocess sleep for one second
35                 printf("I am the child : %d\n",getpid());
36                 exit(0);
37             default:            //Parent process
38                 printf("I am the father : %d\n",getpid());
39                 exit(0);
40                 
41         } */
42     return 0;
43 }
vfork_pid.c

result:

 

When running the program, you can see that the program will stop for one second and then print out the ID of the parent-child process. That is to say, the child process will block for one second when it comes in, but it does not run the parent process first, but let the child process run after it has finished.

 

reference material

Linux/Unix system programming manual

Advanced programming in Unix Environment

Linux Programming

Keywords: Linux Programming Unix network

Added by vinny69 on Wed, 13 May 2020 07:56:54 +0300