All about programming in GNU/LINUX

Program to show that the child process gets a copy of Data , Heap and Stack Segments from the parent process across a fork call in GNU/LINUX

Local Variables are stored in Stack. Register variables are stored in Register. Global variables,  static variables and extern variables are stored in data segment. The memory created dynamically are stored in Heap And the C program instructions get stored in code segment(text segment).

When fork() is invoked the child process gets a copy of parent’s heap,stack and data segment.but the text segment is shared.Here is a simple program to illustrate this.It can be clearly seen in the output that the values are modified just in the child process since it has its own data,heap and stack segments which was copied from the parent across fork() call.

#include<unistd.h>
#include <stdlib.h>
int global=10; //global variable stored in data segment ;
int main()
{
    int stack=10,i; //local variable , stored in stack segment ;
    char *buf;
    buf=(char *)malloc(20);//dynamically allocated variable, stored in heap;
    buf="PARENT";
    i=fork();
    if(i==0)//child process
    {
        global=20;
        stack=20;
        buf="CHILD";
    }
    printf("\n stack=%d,global=%d,buf=%s\n ",stack,global,buf);
    return 0;
}

Image

Advertisements

3 responses

  1. Very good post! We will be linking to this great post on our site.
    Keep up the good writing.

    May 20, 2015 at 1:22 am

  2. Thanks for finally writing about >Program to show that the child
    process gets a copy of Data , Heap and Stack Segments from the parent process across a fork call in GNU/LINUX | hackintoshrao <Liked it!

    June 3, 2015 at 5:08 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s