I am leaing about shared memory and have created this sample program to test things out
//IPC - Shared Memory
#include<stdio.h>
#include<stdlib.h>
#include<linux/ipc.h>
#include<linux/msg.h>
#include<linux/shm.h>
int main(int argc, char* argv[])
{
printf("setting up shared memoryn");
key_t ipc_key;
int shmid;
int pid;
ipc_key = ftok(".",'b');
if((shmid=shmget(ipc_key, 32, IPC_CREAT|0666))==-1)
{
printf("error creating shared memoryn");
exit(1);
}
printf("shared memory created with id %dn",shmid);
//fork a child process
pid = fork();
printf("fork result %dn",pid);
if(pid==0)
{
//child process
//attach the shared memory
int* shm_add_child = (int*)shmat(shmid, 0,0);
printf("child attached to shared mem at address %pn",(void*)shm_add_child);
while(1)
{
printf("%dn",*shm_add_child);
printf("an");
}
//detach from shm
shmdt(shm_add_child);
}
else
{
//parent process
int* shm_add_parent;
shm_add_parent = (int*)shmat(shmid, 0,0);
printf("parent attached to shared mem at address %pn",(void*)shm_add_parent);
*shm_add_parent = 10;
sleep(10);
//detach from shm
shmdt(shm_add_parent);
}
//remove shm
shmctl(shmid, IPC_RMID,0);
exit(0);
}
However when I run it, I get segmentation fault. It seems that my pointers to the shared memory are not right. Also nothing is getting printed from the indefinite while loop in the child process.
ankit@ankit-ThinkPad-W530:~/Desktop/week1_tasks$ ./ipc_sharedmem_a
setting up shared memory
shared memory created with id 5996570
fork result 8703
parent attached to shared mem at address 0xffffffff991aa000
fork result 0
child attached to shared mem at address 0xffffffff991aa000
Segmentation fault (core dumped)
What is going wrong here?
