C fork()进程的工作原理(操作系统)
我对C fork()进程的工作原理(操作系统),c,linux,operating-system,fork,posix,C,Linux,Operating System,Fork,Posix,我对fork()感到困惑。例如,以下代码的输出是什么 #include <sys/types.h> #include <stdio.h> #include <unistd.h> int value = 5; int main() { pid_t pid; pid = fork(); if (pid == 0) { value += 15; return 0; } else if (pid > 0>) {
fork()
感到困惑。例如,以下代码的输出是什么
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int value = 5;
int main() {
pid_t pid;
pid = fork();
if (pid == 0) { value += 15; return 0; }
else if (pid > 0>) { wait (NULL); printf (“Value = %d”, value); return 0}
}
#包括
#包括
#包括
int值=5;
int main(){
pid_t pid;
pid=fork();
如果(pid==0){value+=15;返回0;}
else if(pid>0>){wait(NULL);printf(“Value=%d”,Value);返回0}
}
该函数创建一个新流程,该流程是原始流程的完整副本。新进程有自己的内存和所有变量的副本
在新的子进程中,返回的pid
值为零。子项向其变量值添加15,并在以下行中退出:
if (pid == 0) { value += 15; return 0; }
原始过程中的值为5。原始父进程的pid
大于零,并转到:
else if (pid > 0) { wait (NULL); printf("Value = %d", value); return 0; }
这一行打印:Value=5
函数创建一个新流程,该流程是原始流程的完整副本。新进程有自己的内存和所有变量的副本
在新的子进程中,返回的pid
值为零。子项向其变量值添加15,并在以下行中退出:
if (pid == 0) { value += 15; return 0; }
原始过程中的值为5。原始父进程的pid
大于零,并转到:
else if (pid > 0) { wait (NULL); printf("Value = %d", value); return 0; }
此行打印:Value=5
输出为“Value=5”
fork函数将创建一个具有自己地址空间的新进程(子进程)。子进程将接收父进程数据区域、堆和堆栈的副本。因此,在子进程中修改变量值
不会影响父进程中的变量值
。输出将为“值=5”
fork函数将创建一个具有自己地址空间的新进程(子进程)。子进程将接收父进程数据区域、堆和堆栈的副本。因此,在子进程中修改变量值
不会影响父进程中的变量值
。您可能不知道或不太了解fork
的作用。就像Orest Hera和reffox都说的那样,fork()
跨越了一个新的过程
您还应该知道,父进程(曾经实际调用的fork
)将从fork
获得子进程的pid
子进程从fork
finished的点开始,返回0,从而使进程有机会检查它们是谁:
var x = 7;
pid = fork();
if(pid < 0)
{
perror("failing to create a child process");
return SOME_ERROR;
}
if(pid == 0)
{
/* I'm the child process */
x = 9;
/* only I see that, my dad doesn't even notice that this happened */
...
} else {
/* I'm the parent process */
...
/* waiting for my child to die,
otherwise a zombie will be created,
and I DO mean a zombie */
wait(0);
/* the child is gone, now I can do whatever I want to */
}
var x=7;
pid=fork();
if(pid<0)
{
perror(“未能创建子进程”);
返回一些错误;
}
如果(pid==0)
{
/*我是孩子*/
x=9;
/*只有我看到了,我爸爸甚至没有注意到这件事*/
...
}否则{
/*我是家长*/
...
/*等待我的孩子死去,
否则将创建一个僵尸,
我是说僵尸*/
等待(0);
/*孩子走了,现在我想做什么就做什么*/
}
您可能不知道或不太理解fork
的功能。就像Orest Hera和reffox都说的那样,fork()
跨越了一个新的过程
您还应该知道,父进程(曾经实际调用的fork
)将从fork
获得子进程的pid
子进程从fork
finished的点开始,返回0,从而使进程有机会检查它们是谁:
var x = 7;
pid = fork();
if(pid < 0)
{
perror("failing to create a child process");
return SOME_ERROR;
}
if(pid == 0)
{
/* I'm the child process */
x = 9;
/* only I see that, my dad doesn't even notice that this happened */
...
} else {
/* I'm the parent process */
...
/* waiting for my child to die,
otherwise a zombie will be created,
and I DO mean a zombie */
wait(0);
/* the child is gone, now I can do whatever I want to */
}
var x=7;
pid=fork();
if(pid<0)
{
perror(“未能创建子进程”);
返回一些错误;
}
如果(pid==0)
{
/*我是孩子*/
x=9;
/*只有我看到了,我爸爸甚至没有注意到这件事*/
...
}否则{
/*我是家长*/
...
/*等待我的孩子死去,
否则将创建一个僵尸,
我是说僵尸*/
等待(0);
/*孩子走了,现在我想做什么就做什么*/
}
看一看,这应该是一个有用的教程!看一看,这应该是一个有用的教程!