当前位置:网站首页>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.
边栏推荐
猜你喜欢
随机推荐
STM32启动方式及BootLoader
PTA 指定位置输出字符串(c)
为什么组合优先于继承
CentOS6.5 32bit安装Oracle-11gR2步骤说明
基于STM32F103移植FreeRTOS
去除蜂窝状的噪声(matlab实现)
性能测试(04)-表达式和业务关联-JDBC关联
linux mysql操作的相关命令
caffe ---make all editing error
RPN principle in faster-rcnn
Jmeter BeanShell post processor
FreeRTOS任务创建源码分析
MATLAB代码实现三次样条插值
1006 Sign In and Sign Out (25分)
STemwin中GUI_Exec和GUI_Delay
cnn的输入输出
乘积量化(PQ)
C语言数组题_校门外的树_标记法
MySQL传统方案和通过SSH连接哪个好?
Qt获取EXE可执行文件的上一级目录下的文件