Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fork question 1

Status
Not open for further replies.

Themuppeteer

Programmer
Apr 4, 2001
449
BE
Can anyone explain what happens when I do this?

int* m=new int;
*m=1;

if(fork())
{
*m=0;
}
else
{
while( (*m)>0)
cout<<&quot;looping\n&quot;;
}


I tried this and this is what I found:
in the first process,*m will be 0 while in the second
process, *m will stay 1.
If you do cout<<m<<endl; in both of them,you will see that the address is the same.
Are the 2 processes perhaps in different segmens in memory ?
What happens?

Thnx.
Greetz,

The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
fork() causes a process to be duplicated. The parent's code, data, stack, file descriptors and signal table are all copied. This is why you have the same address for the 'm' pointer.

So...

if(fork()) /*THE PARENT RUNS THIS*/
{
*m=0;
}
else /*THE CHILD RUNS THIS*/
{
while( (*m)>0)
cout<<&quot;looping\n&quot;;
}
 
thnx lordblood for your reply,

the reason I tried this is because that was what I wanted,
I wanted to stop the child by setting a var in mem,since the address is the same, m should change in the child and also in the parent shouldn't it ? Well,it doesn't. It only changes in the place (parent or child) that you change it. Do you know why? after all,it is the same memory,why doesn't it change in both the child and the parent?
(meanwhile I have solved my problem the right way,but I was just curious)
thnx in advance.
Greetz,

The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
Ok, heres my understanding ( I could be wrong ).

The fork() creates a duplicate of the current process. This includes variables and memory offsets. Let say m's address is 4000. This is an offset in the process's memory and it applies only to the current running process. Now if we duplicate it, the new process also contains a 'm' variable with an address of 4000. This is NOT the same variable in memory. It is a duplicated process that has the same offset as the original. This is my understanding of unix processes.

So, these processes are just copies of one another and share no data space. There are functions to allow share memory which is what your looking for. I beleive they include the functions shmget(), shmat(), shmdt() and
shmctl(). I personally have not used these.

Hopefully this helps ...
 
I have used shared memory before in a small test programm.
You have answered exactely my question (I already had a suspicion it where offsets.), thnx a lot for this explanation!
Greetz,

The Muppeteer.

themuppeteer@hotmail.com

Don't eat yellow snow...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top