在fork()期间重复的段? [英] Segments duplicated during fork()?

查看:92
本文介绍了在fork()期间重复的段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究过,在派生期间,父进程的数据和代码段将复制到子进程中.

I have studied that during a fork, the data and code segment of the parent process gets duplicated into the child process.

请参见下面的程序.

int main()
{
   int a = 5;
   pid_t pid;

   pid = fork();

   if(pid == 0)
   {
      printf("In child a = %d",a);
   }

   else
   {
     printf("In parent a = %d",a);
   }

   return 0;
}

此处a在父进程的堆栈段中,因为它是在函数main()中声明的.子进程仅应获取父进程的代码和数据段的副本,而不能获取fork()期间的堆栈.但是当我运行程序时,我可以看到子进程也能够访问变量"a".那意味着以某种方式还将父进程的堆栈也复制到子进程中.

Here a is in the stack segment of parent process as it is declared inside the function, main(). The child process should only get copy of the code and data segment of the parent process and not the stack during fork(). But when I run the program, I can see that the child process is able to access the variable 'a' also. Thats means somehow the stack of parent process is also copied into the child process.

请告诉我这样做的原因,如果我的理解是错误的,请纠正我.

Kindly tell me the reason for this and correct me if my understanding is wrong.

推荐答案

您应检查

You should check the docs again. fork creates an "exact copy of the calling process". Admittedly, there are a lot of exceptions, but the stack is not one of them.

此外,如果未复制堆栈,则检查fork的返回值(几乎总是一个堆栈变量)的非常常见的习惯用法(在代码中也使用)将失败.除非堆栈(包括堆栈指针)被复制,否则pid不会成为.

Also, if the stack wasn't duplicated, the very common idiom (also used in your code) of checking the return value (almost always a stack variable) from fork would fail. There wouldn't be a stack position for pid unless the stack (including stack pointer) was duplicated.

这篇关于在fork()期间重复的段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆