shared array with mmap is not visible between different processes

Viewed 55

I'm trying to write an implementation of malloc and free and a shared stack (that gets commands to push pop and top from clients connecting to server). For some reason when I open 2 clients the memory of the stack is not visible to both of them. (top of the stack is different).

I'll mention that when I implemented this exercise with threads and sbrk it worked perfectly so I suspect it has something to do with how I use the mmap function.

This is the malloc function:


#include<stddef.h>
# include "funcs.hpp"
#include <sys/mman.h>
#include <stdlib.h>


char* memory= (char*)mmap(NULL, sizeof(char)*40000, PROT_READ|PROT_WRITE , MAP_SHARED | MAP_ANONYMOUS, -1, 0);
struct block* mata_data_list=(struct block*)memory;
void initialize(){
    mata_data_list->size= 40000 - sizeof(struct block);
    mata_data_list->is_available=1;
    mata_data_list->next_meta_data=NULL;
}

void split(struct block *old, size_t size){
    struct block *new_block=(struct block*)((int*)old + size + sizeof(struct block));
    new_block->size= (old->size) - size - sizeof(struct block);
    new_block->is_available=1;
    new_block->next_meta_data=old->next_meta_data;
    old->size=size;
    old->is_available=0;
    old->next_meta_data=new_block;
}


void *malloc(size_t number_of_bytes){
    struct block *curr;
    void *result;
    if(!(mata_data_list->size)){
        initialize();
    }
    curr=mata_data_list;
    while((((curr->size) < number_of_bytes) || ((curr->is_available) == 0)) && (curr->next_meta_data != NULL)){
        curr=curr->next_meta_data;
    }
    if((curr->size) == number_of_bytes){
        curr->is_available=0;
        result=(void*)(++curr);
        return result;
    }
    else if((curr->size)>(number_of_bytes + sizeof(struct block))){
        split(curr, number_of_bytes);
        result=(void*)(++curr);
        return result;
    }
    else{
        result=NULL;
        return result;
    }
}

void merge(){
    struct block *curr;
    curr=mata_data_list;
    while((curr->next_meta_data) != NULL){
        if((curr->is_available) && (curr->next_meta_data->is_available)){
            curr->size+= (curr->next_meta_data->size) + sizeof(struct block);
            curr->next_meta_data=curr->next_meta_data->next_meta_data;
        }
        curr=curr->next_meta_data;
    }
}

void free(void* ptr) throw(){
    if(((void*)memory<=ptr)&&(ptr<=(void*)(memory+40000))){
        struct block* curr=(struct block*)ptr;
        --curr;
        curr->is_available=1;
        merge();
    }
}

void *calloc(size_t nitems, size_t size){
    void* ptr = malloc(nitems*size);
    memset(ptr, 0, nitems*size);
    return ptr;
}

This is the relevant server code:

if (!fork()) { // this is the child process
            int pid = getpid();
            handle_stack(pid, new_fd);
        }
0 Answers
Related