1

I am writing a c code for making parent and child process

int main
{
    pid_t =pid;
    pid=fork();
    int a=21;
    if(pid==0)
    {
        a=25;
        printf("%d child \n",&a);
        printf("%d child \n",a);
    }
    if(pid!=0)
    {

        printf("%d parent \n",&a);
        printf("%d parent \n",a);
    }
}

in my output address of variable a printed by both parent and child process are same. I have studied that when we fork a process each child process creates a copy of variables. if this is true then address must be different.

if this is false then when child process executes first then it will change the value at the location where a is stored. but my parent process is printing the value as 21 (according to its copy..)

giorashc
  • 13,691
  • 3
  • 35
  • 71
shiv garg
  • 761
  • 1
  • 8
  • 26

1 Answers1

6

The fork causes the entire address space to be copied. That means variables will have the same addresses in the parent and child processes.

Moreover, the copied address space is independent. If the child changes a value at a particular address, the parent will not see it. It does not matter who executes first, the parent will always print 21 in this case.

You might be thinking of threading, where the address space is shared between multiple threads.

merlin2011
  • 71,677
  • 44
  • 195
  • 329