First time trying to use shared memory ressourced for a educational purpose on my computing class today. I can't understand where the coredump error comes from. The aim of the program is to use two separate thread to wirte into a common table the 26 lettre of the alphabet, one will write in Caps and the other in normal letter.
here is the code I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#define SHMSIZE 52
char tabMaj[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char tabMin[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int main(void){
char c;
int i=0;
int shmid;
char *shm;
if (!fork()){ //soon code
printf("FILS\n");
// create shared memory segment
shmid = shmget(2017, SHMSIZE*sizeof(char), 0666 | IPC_CREAT);
// attach of the segment
shm = shmat(shmid, 0, 0);
char *s = (char *) shm;
for(i=0;i<26;i++){
*(s+1)=tabMin[i];
s=s+2*sizeof(char);
}
shmdt(shm);
}
else{ //father code
printf("PERE\n");
shmid = shmget(2017, SHMSIZE*sizeof(char), 0666 | IPC_CREAT);
shm = shmat(shmid, 0, 0);
char *s = (char *) shm;
for(i=0;i<26;i++){
*(s)=tabMaj[i];
s=s+2*sizeof(char);
}
wait(NULL);
shmdt(shm);
}
return 0;
}
Thanks for helping
since shmid = shmget(2017, SHMSIZE*sizeof(char), 0666 | IPC_CREAT)
creates a shared memory if there is no other shared memory with key:2017 available, you should put that line before forking so that each of processes can use shmid and attach to shared memory by that.
in your source code there each processes can't see shared memory and they each have seperate shared memories (!) created.