Operating system – Why is the address of the variable remains the same in the modified Fork () system call

Please consider the following code snippet.

if (fork() == 0)
{
a = a + 5;
printf("%d, %d ", a, &a);
}
else
{
a = a-5;
printf ("%d, %d ", a,& a);
}

AFAIK, when creating fork(), the parent The virtual address space is copied to the child, and the child & parent share the same physical page until one of them tries to modify. When one of the child & parent modifies the variable, the physical page of the parent is copied to another page of the child page, the physical page The page remains private.
So, here the value of’a’ is different in child& parent. But when it comes to the child and child’s’a’ address, the output is the same. Even if the physical page is different, I do Can’t figure out why the address remains the same.

a’s address is not an actual physical address.

This is a virtual address.
The hardware/operating system layer maps the virtual address to a physical address (not visible to your application).

So even the address With the same number, they will not be mapped to the same physical memory on the ram chip.

PS. It is better to use “%p” when using printf() to print the address (ie pointer)

Please consider the following code snippet.

if (fork() == 0)
{
a = a + 5;
printf("%d, %d ", a, &a);
}
else
{
a = a-5;
printf ("%d, %d ", a,& a);
}

AFAIK, when creating fork(), the parent The virtual address space is copied to the child, and the child & parent share the same physical page until one of them tries to modify. At the moment one of the child & parent modifies the variable, paren The physical page of t is copied to another page of the child page, and the physical page remains private.
So, the value of’a’ here is different in child&parent. But when it comes to children and children’s’a’ When the address is the parent, the output is the same. Even if the physical page is different, I can’t figure out why the address remains the same.

The address of a is not the actual physical address .

This is a virtual address.
The hardware/operating system layer maps the virtual address to a physical address (not visible to your application).

Therefore , Even if the addresses have the same number, they will not be mapped to the same physical memory on the ram chip.

PS. It is better to use “%p” when printing addresses (ie pointers) with printf()< /p>

Leave a Comment

Your email address will not be published.