Results 1 to 3 of 3
Hi,
I used malloc() to allocate some memory,
then i used fork() to create another process
& finally i passed the pointer to that memory location to each of the ...
- 05-25-2007 #1Just Joined!
- Join Date
- May 2007
- Posts
- 18
the pointer, the process & the ugly
Hi,
I used malloc() to allocate some memory,
then i used fork() to create another process
& finally i passed the pointer to that memory location to each of the child processes.
Here's the problem "both the processes are using the same memory location but when i print the contents of that location from within each process, i get different results."
Does anyone have a solution ?
Here's the code for each forked process
void s1(char *C)
{
time(&t);
printf("1 : %d %d %c %d\n",C,*C,*(C+1),t); // t is time
*C=1; // C is the pointer
*(C+1)='a';
printf("1 : %d %d %c %d\n",C,*C,*(C+1),t);
}
void s2(char *C)
{
sleep(1);
printf("2 : %d %d %c %d\n",C,*C,*(C+1),t);
while(t-st<10) { //t is current time, st is start time
if(*C==1){
time(&t);
break;
}
time(&t);
}
printf("2 : %d %d %c %d\n",C,*C,*(C+1),t);
}
- 05-25-2007 #2
So C is the same address in each process. Okay. Have you initialized the value of C+1? Because you do have a race condition here: it is possible that s2 is reading the value after *C = 1, but before *(C+1) = 'a'.
You could probably use a mutex or something to get these to work the way you want. But for now, try initializing *(C+1) and see if that's the value that you're reading.DISTRO=Arch
Registered Linux User #388732
- 05-25-2007 #3Just Joined!
- Join Date
- May 2007
- Posts
- 18
ooops
there was a huge mistake, the memory wasnt shared on the first place, got it running after using shmget() and shmat()
Thanks anyway.


Reply With Quote