Fork analysis of Linux process creation

Time:2021-7-8

   inLinuxIn the kernel, processes are maintained all the time. From process creation to process destruction, every environment has complex details. IntroductionLinuxHow does the kernel create processesforkThe creation of functions and subprocesses is also crucial for understanding multi process development.

catalogue

Fork() function

First, let’s look at the fork() function, which creates a child process. The header file and function prototype are as follows

#include 

//Parameters 	:  void 
//Return value: PID_ T created child process ID
pid_t fork(void);

Return value: fork() return value will be returned twice, respectively in the parent process and the child process.

  1. Returns the ID of the child process in the parent process and 0 in the child process. So you can go through itforkTo distinguish the parent process from the child process.
  2. Returns in the parent process-1, indicating that the creation of a child process failed, and settingerrorno。 For example, the following two situations lead to the creation failure:
  • At present, the number of processes in the system has reached the upper limit specified by the systemerrnoThe value of is set toEAGAIN
  • There is not enough memory in the systemerrnoThe value of is set toENOMEM

Fork() example

Next, create a child process to show the execution order of the parent process and the child process.

#include 
#include 


int main(){
	//Create process
	pid_t pid = fork();

	//Determine whether the current process is a parent process or a child process
	if (pid > 0){ 			//  Process number > 0 is the process number of the child process, which is the parent process
		printf("pid: %d\n", pid);
		printf("I am parent process, pid: %d, ppid: %d\n", getpid(), getppid());
	}
	else if (pid == 0){ 		//  Process number = = 0, indicating that it is a child process
		printf("I am child process, pid: %d, ppid: %d\n", getpid(), getppid());
	}
	
	for (int i = 0; i < 5; i++){
		printf("pid: %d, i : %d\n", getpid(), i);
        sleep(1);
	}
	return 0;
}

Compile and execute. You can see that the child process is created successfully, and the two processes are executed at the same time. The parent process ID is 412552, and the child process ID is 512553. Because the sleep() function blocks the function, the parent process and the child process execute alternately.

fork-

Virtual address space of parent-child process

After creating a process by fork function, you can judge whether it is a parent process or a child process by the return value. For how to execute the parent process and the child process, the following describes how to execute the parent-child process after calling the fork function, and how to reflect it in the virtual address space of the process.

  
   first, let’s take a look at the execution order of the above example. After the parent process executes fork, it returns the child process ID,pidGreater than 0, so outputif(pid>0)The content of.
父进程

   after the subprocess is successfully created, it returns 0 in the subprocess and executes from the current position, sopid=0Will outputelsesentence.
子进程执行魂虚

   for a virtual address, the child process copies the virtual address space of the parent process. So,After fork, the user area of the child process is the same as that of the parent processAnd so will itCopy kernel area contentIt’s justPID of processDifferent.

父子进程的虚拟地址空间

   forStack space variables, will also be copied intact to the stack space of the child process. However, the two variables do not affect each other, the parent process change variables will not affect the child process variables. See the following program to show the use of stack space variables in the parent-child process.

#include 
#include 


int main(){
	//Create process
	pid_t pid = fork();

	//Local variable
	int num = 10;

	//Determine whether the current process is a parent process or a child process
	if (pid > 0){ 			//  Process number > 0 is the process number of the child process, which is the parent process
		printf("I am parent process, pid: %d, ppid: %d\n", getpid(), getppid());

		printf("parent process num : %d\n", num);
		num += 10;
		printf("parent process num + 10 : %d\n", num);

	}
	else if (pid == 0){ 		//  Process number = = 0, indicating that it is a child process
		printf("I am child process, pid: %d, ppid: %d\n", getpid(), getppid());

		printf("child process num : %d\n", num);
		num += 100;
		printf("child process num + 100 : %d\n", num);
	}
	
	return 0;
}

When compiling and executing, you can see the local variables in the parent processnumIt does not affect the local variables of the subprocess.
num
  
Share on read, copy on writetechnology
   in fact, to be precise, LinuxforkIt’s throughCopy on write(copy on write) implementation. Copy on write is a technology that can delay or even avoid copying. More specifically, after the fork statement is executed, the kernel does not copy the entire address space of the parent process, but theParent child processes share the address space of the parent process(at this time, the parent-child process is a read-only instruction for the address space). When the parent process or the child process writes instructions, the child process will copy an address space, so that the parent-child process has its own virtual address space and can write instructions in its own address spaceWrite operation。 in other words,Resources are copied only when they need to be written. Before that, they will only be shared in read-only mode

  For file resources, the parent and child processes after fork share files. The file descriptor tables of the parent and child processes after fork point to the same file table. The reference count increases and the shared file offset pointer increases.

The     fork function is introduced here. This article introduces the process of creating a child process, and understands the sharing and replication of virtual address space between parent and child processes. In multithreading development, it is easy to analyze the execution order and memory sharing of parent-child process.

Pay attention, don’t get lost.One key three linksIt’s my biggest support. Welcome to pay attentionProgramming town, a little bit higher every day.