Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

gcc - is data shared between processes when we use fork in c?

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;
}

Here is the output of the program.

 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...