confusing fork system call

Posted by benjamin button on Stack Overflow See other posts from Stack Overflow or by benjamin button
Published on 2010-03-25T04:20:22Z Indexed on 2010/03/25 4:23 UTC
Read the original article Hit count: 311

Filed under:
|
|
|

Hi,

i was just checking the behaviour of fork system call and i found it very confusing. i saw in a website that

Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces

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

int main(void)
{
pid_t pid;
char y='Y';
char *ptr;
ptr=&y;
pid = fork();
if (pid == 0)
{
y='Z';
printf(" *** Child process  ***\n");
printf(" Address  is %p\n",ptr);
printf(" char value is %c\n",y);
sleep(5);
}
else
{
sleep(5);
printf("\n ***parent process ***\n",&y);
printf(" Address  is %p\n",ptr);
printf(" char value is %c\n",y);
}
}

the output of the above program is :

 *** Child process  ***
 Address  is 69002894
 char value is Z

 ***parent process ***
 Address  is 69002894
 char value is Y

so from the above mentioned statement it seems that child and parent have separet address spaces.this is the reason why char value is printed separately and why am i seeing the address of the variable as same in both child and parent processes.?

Please help me understand this!

© Stack Overflow or respective owner

Related posts about c

    Related posts about unix