Why can’t get a sigsegv or something when I read and write from the same shared memory segment? Is it normal? Why don’t I get any error?
(I know that I don’t call shmclt or shmdt) (:
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int parent(char*);
int child(char*);
int main ()
{
int shmid = shmget (0xACA0E5,30*sizeof(char),
IPC_CREAT | S_IRUSR | S_IWUSR);
char *shared = (char*) shmat(shmid,0,0);
if (fork())
return parent(shared);
else
return child(shared);
}
int parent (char* shared)
{
while(1)
{
printf("F: %s",shared);
sprintf(shared,"FATHER \t%p\n",shared);
}
}
int child(char* shared)
{
while(1)
{
printf("C: %s",shared);
sprintf(shared,"CHILD \t%p\n",shared);
}
}
Yes, that behaviour is perfectly normal. The operating system does not prevent you from overwriting your own data in the shared memory segment. If you want to avoid this, you will need to introduce some kind of IPC that synchronises access to the shared memory area.