子进程(由 fork() 创建)访问父进程的堆部分是否合法?

发布于 2024-12-11 19:18:34 字数 719 浏览 0 评论 0原文

子进程可以访问(读和写)父进程的堆地址空间吗? 以下是我在 http://www.ideone.com/R5vDT 尝试的程序,该程序运行成功:

int main(){
        int *p = (int*)malloc(sizeof(int));
        if(fork()){
        //parent process
                *p = 25;//Write
                printf("Parent %d: %d %p\n", getpid(), *p, p);//Read
        }else{
        //child process
                *p = 15;//write
                printf("Child %d: %d %p\n", getpid(), *p, p);//read
        }
        return 0;
}     

输出是:

Parent 30597: 25 0x9781008
Child 30600: 15 0x9781008

我已阅读有关 COW(写入时复制)的内容,但即使在写入操作之后,p 指向的地址也是相同的。操作系统不应该因为一个进程正在访问其地址空间之外的内存而引发异常吗?

Can a child process access(read and write) parent process's heap address space?
Following is the program i tried at http://www.ideone.com/R5vDT which is running successfully:

int main(){
        int *p = (int*)malloc(sizeof(int));
        if(fork()){
        //parent process
                *p = 25;//Write
                printf("Parent %d: %d %p\n", getpid(), *p, p);//Read
        }else{
        //child process
                *p = 15;//write
                printf("Child %d: %d %p\n", getpid(), *p, p);//read
        }
        return 0;
}     

Output is:

Parent 30597: 25 0x9781008
Child 30600: 15 0x9781008

I have read about C-O-W (copy on write) but addresses pointed by p are same even after write operation. Should NOT the Operating System raise an exception because one process is accessing memory outside it's address space?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月染过的梦 2024-12-18 19:18:34

好吧,这两个进程有自己的地址空间,即使它们没有访问相同的内存,每个进程看起来也是一样的。然而,许多操作系统实现了一种称为写时复制的功能,这意味着内存不会在您调用 fork 时复制,而是在其中一个进程修改内存时复制。只要没有进程写入内存,它们就会从同一内存中读取。当其中一个尝试修改内存时,会引发某种类型的异常并复制内存,以便它们都拥有一个私有内存区域,任何其他进程都无法访问。

Well, the two processes have their own address spaces that to each of the process looks the same, even though they are not accessing the same memory. However, many operating systems implement something called copy-on-write, meaning that the memory isn't copied at the time you call fork but rather when one of the processes modifies the memory. As long as no process is writing to the memory, they are reading from the same memory. When one of them tries to modify the memory, some type of exceptions is raised and the memory is copied so that they both have a private area of memory, inaccessible to any other process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文