I'm trying to use shared memory. So far I have
Code:
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PATH_LEN 1024
#define ARRAY_SIZE 50
typedef struct _task{
char path [MAX_PATH_LEN];
char thread_id[MAX_PATH_LEN];
char op;
int index;
}task;
typedef struct _sharedMem{
int lastIn;
int numTasks;
sem_t mutex;
int size;
task array [ARRAY_SIZE];
}sharedMem;
int main(void){
int i;
int id = shmget(1234, sizeof(sharedMem), IPC_CREAT|0777);
sharedMem* shMem = shmat(id, NULL, 0);
printf("init 1\n");
shMem->lastIn = 0;
printf("init 2\n");
shMem->numTasks = 0;
printf("init 3\n");
sem_init(&(shMem->mutex), 0, 1);
printf("init 4\n");
shMem->size = ARRAY_SIZE;
for(i = 0; i < shMem->size; i++){
strcpy(shMem->array[i].path, " ");
}
return 1;
}
The output for this is
Code:
init 1
Segmentation fault
I have no idea why. Do we have to do something to the structure before start using it?
If so what?