当有全局指针时,分叉进程如何不会相互影响? [英] How come forked processes do not affect each other when there is a global pointer?

查看:148
本文介绍了当有全局指针时,分叉进程如何不会相互影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 fork()函数会创建一个与其父项相同的进程,但仅仅因其具有的PID而不同。它们最初具有相同的变量,并且对这些变量所做的更改不会互相影响。但是当共享一个全局指针变量会发生什么?



我写了一些代码并打印出结果。看起来,父进程和子进程都有指向相同内存位置的指针,但是对这些内存位置进行了更改,即 * p = 1 * p = 2 在孩子中,不会相互影响。另请注意,我使父进程 wait(NULL)直到子进程退出。因此,子进程改变了具有与父进程的指针相同内存地址的指针指向的值。


$ b 我知道何时 fork() 被调用,父进程克隆所有东西:寄存器,程序计数器等,但这怎么可能?子进程退出后,父进程是否应该改变其变量的值?是否由于系统将所有内容(包括父进程的指针变量)放到堆栈上,并在子进程终止时弹出它们?

解决方案

当一个进程分叉时,新进程是针对所有(?)意图和目的的原始副本,并拥有自己的虚拟地址空间,文件描述符等在一个相当简单的观点中,相同的内存地址实际上会指向每个进程的不同物理内存地址 - 您可以使用两个指向完全不同数据的相同指针。



当然,在现代操作系统中事情并不那么简单。例如, fork()实际上不会复制所有内容,因为这会浪费处理器时间和内存。内核利用一些页表操作来实现 copy-on-write 内存复制。此外,为了性能和正确性的原因,可以在某种程度上控制哪些资源实际上会克隆到子进程。


I know the fork() function creates a process which is identical to its parents, only differs by the PID it has. They have the same variables initially, and changes made to these variables do not affect each other. But what happens when a global pointer variable is shared?

I have written some code and printed out the results. It appears that the parent and the child process have the pointer pointing to the same memory location, however changes made to these memory locations, i.e. *p = 1 in parent and *p = 2 in child, do not affect each other. Also note that I make the parent process wait(NULL) until the child process exits. So the child process changes the value pointed by the pointer having the same memory address of the parent process' pointer.

I know when fork() is called, parent process clone everything: registers, program counters etc. But how is that possible? Shouldn't the parent process have its variable's value changed after the child process exits? Is it due to the system puts everything (including the parent process' pointer variable's) onto stack and pops them when the child is terminated?

解决方案

When a process is forked, the new process is for all(?) intents and purposes a copy of the original, with its own virtual address space, file descriptors e.t.c. In a rather simplistic view, the same memory address will actually point to a different physical memory address for each process - you can have two equal pointers that point to completely different data.

Naturally, in modern operating systems things are not quite as simple. fork(), for example, does not actually copy everything as that would be a waste of both processor time and memory. The kernel makes use of a bit of page table manipulation to implement copy-on-write memory duplication. Additionally, it is possible to control to some degree which resources will be actually cloned to the child process, for both performance and correctness reasons.

这篇关于当有全局指针时,分叉进程如何不会相互影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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