samedi 18 avril 2015

Making a shared data structure in c

I have created a data structure in my C program as follows,



typedef struct {
int *array;
size_t used;
size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
a->array = (int *)malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}

void insertArray(Array *a, int element) {
if (a->used == a->size) {
a->size *= 2;
a->array = (int *)realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}

void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}


Then I'm adding some data to that data structure from an external text file using following method,



Array read_ints (const char* file_name)
{
Array numbers;
initArray(&numbers,5);

FILE* file = fopen (file_name, "r");
int i = 0;
int count = 0;

fscanf (file, "%d,", &i);
insertArray(&numbers,i);
while (!feof (file))
{
//printf ("%d ", i);
fscanf (file, "%d,", &i);
insertArray(&numbers,i);
}
fclose (file);
return numbers;
}


Now what I need to do is, I need to make the 'Array' data structure a shared memory portion so that the both child and parent processes on my program could access that data structure. I have no idea on how to make it a shared memory. I'm aware that the shmget() system call can be used to get a shared memory in UNIX environment. But i cannot see how to use that system call on this scenario. Please help me.


Aucun commentaire:

Enregistrer un commentaire