Code:
#include <stdio.h>#include <semaphore.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "tlpi_hdr.h"
#include "error_functions.h"
//DECLARE GLOBAL VARIABLES/ARRAYS
FILE *fp;
int *address;
//DEFINE POTIONS
typedef struct potion{
char *name;
int count;
} potion;
//DEFINE MORE GLOBAL VARIABLES/ARRAYS
potion all_potions[1000];
//ERROR CHECKING FOR SHAREMEMORY
static void usageError(const char *progName)
{
fprintf(stderr, "Usage: %s [-cx] name size [octal-perms]\n", progName);
fprintf(stderr," -c Create shared memory (O_CREAT)\n");
fprintf(stderr, " -x Create exclusively (O_EXCL)\n");
exit(EXIT_FAILURE);
}
//READ FILE FUNCTION
void readFile(){
char temp_name[200];
char str[200];
if((fp = fopen("inventory_input.txt", "r")) == NULL){
printf("Cannot open inventory_input.txt file.\n");
exit(1);
} else {
while(! feof(fp)){
fscanf(fp,"%s",str);
int *lines_left = malloc(sizeof(int));
int *lines_count = malloc(sizeof(int));
*lines_left = atoi(str);
*lines_count = 0;
while(*lines_left>0){
// printf("%d lines left\n",*lines_left);
fscanf(fp, "%s",temp_name);
all_potions[*lines_count].name = (char *)malloc(100);
strcpy(all_potions[*lines_count].name,temp_name);
fscanf(fp, "%s",str);
all_potions[*lines_count].count = atoi(str);
printf("%s: %s left\n",temp_name,str);
*lines_left=*lines_left-1;
*lines_count=*lines_count+1;
}
break;
}
}
}
//MAIN FUNCTION
int main(int argc, char* argv[]){
int opt, fd, flags;
mode_t perms;
size_t size;
void *addr;
size=sizeof(potion)*1000;
fd = shm_open("butt",O_CREAT,0);
//CONDITIONAL FOR SHARE MEM
printf("Resized to %ld bytes\n", (long) size);
addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
system("pause");
getchar();
readFile();
memcpy(addr, all_potions, size);
shm_unlink("butt");
exit(EXIT_SUCCESS);
return 0;
}
So in my main function, I'm trying to create a shared memory space to store an array of potions. I have defined potions in typedef format above.
I figured size=sizeOf(potion)*1000 would allow 1000 potions.
When I do the memcpy into the shm, however (I have checked, and the instantiation of it works as shows up in /dev/shm)
It just seg faults, no matter what.
I'm new to all of this and my professor is unavailable for the week and we're allowed to research. Any suggestions? Am i not allocating enough? Are my memcpy parameters wrong?