سؤال

I am having difficulty understanding the output of the programe. After using fork(), the memory location of the variable inmem is showing the same. Can someone please explain this! Thanku

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int inmem = 9;
int pid = fork();

if(!pid)
{
    printf("child inmem %d %p\n", inmem,&inmem);
    inmem = 8;
    printf("child inmem %d %p\n", inmem, &inmem);

}

else
{
    printf("parent inmem %d %p\n", inmem, &inmem);
    inmem = 5;
    printf("parent inmem %d %p\n", inmem, &inmem);

}
return 0
}

OUTPUT-

parent inmem 9 0x7ffff0acdfc8
parent inmem 5 0x7ffff0acdfc8
child inmem 9 0x7ffff0acdfc8
child inmem 8 0x7ffff0acdfc8
هل كانت مفيدة؟

المحلول 2

After fork() child will have separate address space. This address space refers to the virtual address space. So parent and child will have same address that is virtual address.

OS will map this virtual address in separate address space with different physical address

نصائح أخرى

fork creates an exact copy of your process, with regard to your code and adresses. This is already necessary because the code after the fork executes the same way as before and has the same acess to variables. However, once the processes are forked, they no longer are synchronized, so allocating a new memory may yield different addresses.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top