Sharing an array of structures using mmap

I am trying to create an array of structures that is shared between parent and child processes. When you try to access array data, a segmentation error occurs.

I am sure that the problem is related to the way I use pointers, as this is an area that is not very convenient for me.

Please note that I edited most of the code that did not seem relevant.

/* structure of Registration Table */
struct registrationTable{
    int port;
    char name[MAXNAME];
    int req_no;
};

main() {

    /* the registrationTable is to be a shared memory space with each child
    process able to access and update. No concurrency controls are 
     implemented. The parent process is responsible for cleaning up after
     the kiddies.
 */
struct registrationTable base_table[REG_TABLE_SIZE];
for (int i = 0; i < REG_TABLE_SIZE; i++) {
    base_table[i].req_no = 0;
    memset(base_table[i].name, '\0', MAXNAME);
    base_table[i].port = 0;
}

printf("\nMapping Shared Memory\n");

//set up shared memory space
//void *mmap(void *addr, size_t length, int prot, int flags,
    //              int fd, off_t offset);
//      addr = NONE, prot = PROT_NONE, flags = MAP_SHARED 
struct registrationTable *table = mmap(base_table, sizeof(base_table),
                        PROT_READ | PROT_WRITE, 
                        MAP_SHARED | MAP_ANONYMOUS,
                        -1, 0);

while(1){
    pid_t child = fork();

    if (child == 0) {//is child

        for(int i = 0; i < REG_TABLE_SIZE; i++) {

            printf("\nExamining table looking for client at %s port: %d\n", 
                    packet_reg.data, clientAddr.sin_port);

            printf("\ntable[1].req_no: %d", ta[i].req_no);

                            //segmentation fault on next line
            if (strcmp(table[i].name, packet_reg.data) == 0 
                    && table[i].port == clientAddr.sin_port) {
                table[i].req_no++;
}
+3
source share
1 answer

You did not initialize the contents tableafter it was assigned to mmap. Thus, it contains trash. Thus, there strcmp(table[i].name, packet_reg.data)is a great chance to flip allocated buffers and gain access, for example. unallocated memory.

  • initialize the table correctly;
  • Use strncmp to compare there.
+3
source

All Articles