当前位置:网站首页>fork creates multiple child processes

fork creates multiple child processes

2022-08-09 11:15:00 XV_

references:
[1] how to create two processes from a single Parent
[2] fork() in C
[3] linux中forkA method to create multiple child processes at the same time

fork的本质,就是复制,Make a copy of the current process,The two processes then execute concurrentlyfork后面的语句,区别就是,子进程的fork返回值是0,父进程的fork返回值是子进程的pid,This is also the way to differentiate between parent and child processes,至于其他的内容,在forkThe things before the two processes are the same.

Give a template for a parent process and a child process

int fd = fork();
if(fd < 0){
    
	exit(1);
} else if(fd == 0){
    
	// child code
} else {
    
	// father code
}

对于创建1parent process and 2个子进程,也是一样的道理

int fd1,fd2;

fd1 = fork();
if(fd < 0){
    
	exit(1);
} else if(fd == 0){
    
	// child1 code
} else {
    
	fd2 = fork();
	if(fd2 < 0){
    
		exit(1);
	} else if(fd2 == 0){
    
		// child2 code
	} else {
    
		// father code
	}
}

Create the child process first1,The parent process then resumes execution,创建子进程2,最后,3Each process is able to execute its own code within the framework.

This is the best framework to use,能够将3Each process is identified and differentiated,But if creatednchild process will be very troublesome.

因此,根据不同需求,Other spellings are also possible

for(int i = 0; i < n; i++){
    
	int fd = fork();
	if(fd < 0){
    
		exit(1);
	} else if(fd == 0){
    
		// child i code
		break;
	} else {
    
		// father code
	}
}

The most important thing isbreak,It is guaranteed that the child process will not create further child processes.

Then the child process can actually do its own thing,such as executingexec family,Execute other processes or something.

另外值得一说的是,If the parent process does not wait for the child process to finish before ending,shellDisplay confusion occurs.

就像下面这样,But it just shows confusion,You can directly enter the command normally.
在这里插入图片描述

reference
[1] Using fork() in simplest form need to hit enter to finish execution
[2] Why do shells call fork()?

至于为什么,那是因为,当shellafter executing the command,也会Create a child firstshell,然后执行exec,Then execute the command you want to execute,执行结束后,Return to the current oneshell.

我们用shellThe parent process is executed,结束后返回,就显示[email protected]:$了,And the child process is still executing,并且向shell输出了child process,Hence the above situation,But it just shows the problem,正常向shellJust enter the command.

原网站

版权声明
本文为[XV_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091103197763.html