-
fork with shared memory
Hello!
I created two processes thanks fork. Now I would like to send 10 int values from the child process to the father process.
Something like that:
son writes int in shared memory
father reads int from shared memory
son writes int in shared memory
father reads int from shared memory
and so on.
Code:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
/*============================================================================*/
int main(int argc, char **argv)
{
int shmid, shmflg, permflg, res, son;
volatile int*data;
void *map_adr;
permflg = (SHM_R|SHM_W) | ((SHM_R|SHM_W)>>3) | ((SHM_R|SHM_W)>>6);
shmflg = IPC_CREAT | IPC_EXCL | permflg;
shmid = shmget(IPC_PRIVATE, 8*1024, shmflg);
map_adr = shmat(shmid, NULL, 0);
data = (int *)map_adr;
*data = 1;
if((son = (fork() == 0))) {
map_adr = shmat(shmid, NULL, 0);
while(*data != 0);
*data = *data + 1;
//printf("value is %d\n", *data);
//*data = 1;
}
else {
while(*data != 10) {
printf("value is %d\n", *data);
}
}
res = shmdt(map_adr);
if(!son)
res = shmctl(shmid, IPC_RMID, NULL);
return 0;
}
I think my problem is my while-loop because it stops after data reaches 1. I don't know how to fix it.
Thanks for your help!
-
This:
is an infinite busy loop. There is no block associated with it.
Fixing that will move you on to the next set of problems:
1) that the two forks do not synchronously alternate; ie, the child loop could happen several times in a row while the parent loop happens only once.
2) that as a consequence of #1, the parent while() loop condition may very likely skip ever being met, and so become endless.
3) that the child fork is certainly endless.