Consider the following code snippet.
if (fork() == 0)
{
a = a + 5;
printf("%d, %d \n", a, &a);
}
else
{
a = a - 5;
printf ("%d, %d \n", a,& a);
}
AFAIK, when fork() is made, the virtual address space of parent is copied to the child and both child & parent share the same physical pages until one of them tries to modify. The moment one of the child & parent modifies a variable, the physical page of parent is copied to another page for child and the physical pages remain private. So, here value of 'a' is different in child & parent. But when it comes for the addresses of 'a' in child & parent, the output is same. I am not able to figure out why the address remains same even if the physical pages are diffrent.
The fork operation creates a separate address space for the child. The child process has an exact copy of all the memory segments of the parent process.
Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.
all kind of data pointers, memory, variable will be duplicate in a separate memory for the child process created with fork.
No, since global variables are not shared between processes unless some IPC mechanism is implemented. The memory space will be copied. As a consequence, the global variable in both processes will have the same value inmediately after fork, but if one changes it, the other wont see it changed.
fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process. The child process and the parent process run in separate memory spaces.
Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.
The address of a
is not the actual physical address.
It is a virtual address.
The hardware/OS layer maps virtual addresses to physical addresses (invisibly to your application).
So even though the addresses have the same number
they do not map to the same physical memory on your ram chip.
PS. When printing the address (ie pointer) using printf() best to use "%p"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With