当我们在c中使用fork时,进程之间是否共享数据? [英] is data shared between processes when we use fork in c?

查看:20
本文介绍了当我们在c中使用fork时,进程之间是否共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个 C 程序中,数据不会在进程之间共享,即父进程和子进程.孩子有自己的数据,父母有自己的数据,但指针显示两个进程的地址相同.它是如何在后台完成的?fork 会生成相同数据的副本吗?如果是这样,那么我们对两个进程都有相同的指针地址.还是由于为每个进程复制的静态分配的数据,并且每个进程的数据是独立的?我想知道它是如何完成的?

In this C program, data is not being shared between process i.e. parent and child process. child has it's own data and parent has it's own data but pointer is showing the same address for both processes. How it is being done on background? Does fork generates copies of same data? if so then we have the same pointer's address for both processes. Or is it due to the statically allocated data that is being copied for each process and the data is independent for each process? I want to know how it is being done?

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>

int main()
{
    //Static Array
    int X[] = {1,2,3,4,5};
    int i, status;

    //The fork call
    int pid = fork();

    if(pid == 0) //Child process
    {
        //Child process modifies Array
        for(i=0; i<5; i++)
            X[i] = 5-i;
        //Child prints Array
        printf("Child Array:	");
        for(i=0; i<5; i++)
            printf("%d	", X[i]);
        printf("
Array ptr = %p
", X);
     }
     else //Parent process
     {
        // Wait for the child to terminate and let 
        // it modify and print the array
        waitpid(-1, &status, 0);

        //Parent prints Array
        printf("Parent Array:	");
        for(i=0; i<5; i++)
           printf("%d	", X[i]);
        printf("
Array ptr = %p
", X);
        }
    return 0;
}

这是程序的输出.

 1  Child Array:    5   4   3   2   1   
 2  Array ptr = 0x7fff06c9f670
 3  Parent Array:   1   2   3   4   5   
 4  Array ptr = 0x7fff06c9f670

当子进程修改数组时,它应该也修改了父进程的数据.后台发生了什么?

When child process modifies array it should have also modified the data of parent process. What is going on in background?

推荐答案

当你 fork 一个新进程时,新的子进程是父进程的 副本.这就是为什么指针等是相等的.由于虚拟内存的奇妙之处,两个进程可以拥有相同的内存映射,但仍然使用不同的内存.

When you fork a new process the new child process is a copy of the parent process. That's why pointers etc. are equal. Due to the wonders of virtual memory two processes can have the same memory map, but still be using different memory.

这篇关于当我们在c中使用fork时,进程之间是否共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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