当前位置:网站首页>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.
边栏推荐
猜你喜欢
随机推荐
margin出bug---margin失效
prometheus接入mysqld_exporter
综述文章的写法
PTA 矩阵运算
OpenSSF's open source software risk assessment tool: Scorecards
cnn的输入输出
激光条纹中心提取——灰度重心法
c语言函数的递归调用(汉诺塔问题,楼梯递归问题等)
Preparation for gold three silver four: how to successfully get an Ali offer (experience + interview questions + how to prepare)
1006 Sign In and Sign Out (25分)
Antdv+Asp.net WebApi开发学生信息管理系统(一)
OpenSSF的开源软件风险评估工具:Scorecards
Arduino学习总结 + 实习项目
Input and output of cnn
MDK添加注释模板
1005 Spell It Right (20分)
详细的np.matmul / np.dot / np.multiply / tf.matmul / tf.multiply / *
为什么组合优先于继承
Quartz分布式实现
torch.stack()的官方解释,详解以及例子