Pli*_*ken 18 c linux operating-system process
下面是Fork函数的实例.下面也是输出.我的主要问题是如何调用一个fork来调用值的变化.所以pid1,2和3从0开始,随着叉子的发生而改变.这是因为每次fork发生时,值都会复制到子节点,并且父节点中的特定值会发生变化吗?基本上,值如何通过fork函数改变?
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1==0){
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
pid3=fork(); /* D */
if(pid3==0) {
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0))
printf("Level 1\n");
if(pid1 !=0)
printf("Level 2\n");
if(pid2 !=0)
printf("Level 3\n");
if(pid3 !=0)
printf("Level 4\n");
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
然后这是执行.
----A----D--------- (pid1!=0, pid2==0(as initialized), pid3!=0, print "Level 2" and "Level 4")
| |
| +----E---- (pid1!=0, pid2!=0, pid3==0, print "Level 2" and "Level 3")
| |
| +---- (pid1!=0, pid2==0, pid3==0, print "Level 2")
|
+----B----C---- (pid1==0, pid2!=0, pid3!=0, print nothing)
| |
| +---- (pid1==0, pid2==0, pid3==0, print nothing)
|
+----C---- (pid1==0, pid2==0, pid3!=0, print nothing)
|
+---- (pid1==0, pid2==0, pid3==0, print nothing)
Run Code Online (Sandbox Code Playgroud)
理想情况下,我希望看到它的解释,因为这种方式对我有意义.*是我的主要困惑所在.例如pid1 = fork();,当孩子分叉时会创建一个包含父级所有值的进程,但它是否会向父亲pid1传递一个值,例如1.这意味着孩子的pid 1 = 0,pid2 = 0和pid3 = 0,父母的pid1 = 2,pid2和3等于0?
Rah*_*Jha 24
系统调用fork()用于创建进程.它不需要参数并返回进程ID.fork()的目的是创建一个新进程,该进程成为调用者的子进程.创建新的子进程后,两个进程将执行fork()系统调用之后的下一条指令.因此,我们必须区分父母与孩子.这可以通过测试fork()的返回值来完成
Fork是一个系统调用,您不应该将其视为普通的C函数.当fork()出现时,您有效地创建了两个具有自己的地址空间的新进程.在fork()调用之前初始化的变量在地址空间中存储相同的值.但是,在任一进程的地址空间内修改的值在其他进程中不受影响,其中一个进程是父进程,另一个进程是子进程.因此,如果,
pid=fork();
Run Code Online (Sandbox Code Playgroud)
如果在后续的代码块中检查pid的值,则会在代码的整个长度上运行两个进程.那么我们如何区分它们呢?Fork再次是一个系统调用,这里有区别.在新创建的子进程中,pid将存储0,而在父进程中它将存储一个正值.pid中的负值表示fork错误.
当我们测试pid的值以查找它是否等于零或大于它时,我们有效地发现我们是在子进程还是父进程中.
int a = fork();
Run Code Online (Sandbox Code Playgroud)
创建一个重复的进程"clone?",它共享执行堆栈.父和子之间的区别是函数的返回值.
返回0的孩子,父母获得新的pid.
每次复制堆栈变量的地址和值.执行在代码中已经到达的位置继续.
在每个fork,只修改一个值 - 返回值fork.