I was just checking the behavior of the fork system call and I found it very confusing. I saw on the website that
Unix will make an exact copy of the parent address space and pass 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); } }
output of the above program:
*** Child process *** Address is 69002894 char value is Z ***parent process *** Address is 69002894 char value is Y
therefore, from the above statement, it seems that the child and the parent have separet address spaces. It is for this reason that the char value is printed separately and why I see the address of the variable as the same in both the child and the parent processes.
Please help me figure this out!
source share