By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,294 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

fork(): Child Memory from Parent

P: 2
On a HPUX, a CPP program. In main() defined a variable as int x = 900, called fork(), changed value of x as 89 in child process. Printed the address of x and value of x in child process and also in the parent process after wait(0).

Doubt
--------
Both in child and parent process, the address of x (&x) was same.
Since the address of x is same, the value shows different in parent and child.
Could you please reply. I got confused.


int main()
{

int x = 900;
int *ptr = &x;
cout << "\n &x x " <<&x<< " " << x; OUTPUT=> 0x7b03a490 900

if (fork())
{
cout << "\n &x x " <<&x<< " " << x; OUTPUT=> 0x7b03a490 900
wait(0);
cout << "\n walk up parent";
cout << "\n &x x " <<&x<< " " << x; OUTPUT=> 0x7b03a490 900
return(0);
}
else
{
x = 89;
cout << "\n &x x " <<&x<< " " << x; OUTPUT=> 0x7b03a490 89
exit(0);
}
cout << "\n parent is here exit";
return(0);
}
Jun 8 '07 #1
Share this Question
Share on Google+
3 Replies


100+
P: 256
when you fork() each process gets it's own copy of everything. If you want to have the parent process see changes to variables that the child process makes (or vice-versa) you will have to use shared memory.
Jun 9 '07 #2

P: 2
when you fork() each process gets it's own copy of everything. If you want to have the parent process see changes to variables that the child process makes (or vice-versa) you will have to use shared memory.

My question is though the parent and child process print the same address (&x) of the variable x, shows different values in parent and child.
Jun 9 '07 #3

Expert 10K+
P: 11,448
My question is though the parent and child process print the same address (&x) of the variable x, shows different values in parent and child.
That's what virtual memory is all about; address 42 for your process doesn't
refer to the same real memory location as my process's address 42.

kind regards,

Jos
Jun 9 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.