'Share memory between multiple child processes belonging to same parent
I am trying to create Client/Server application based on master/slave architecture. The parent Server is responsible for handling new socket requests from client and uses fork() in which the client interaction happens.
I want to create a Linked List in the application in which the child processes add nodes and it is accessible to every other child. I have tried creating share memory using mmap and shmget but other processes are not able to read the linked list after the first child creates the list.
node structure:
struct node{
char data[1024];
struct node *next;
};
mmap approach:
void* create_shared_memory(size_t size){
int protection = PROT_READ |PROT_WRITE;
int visibility = MAP_SHARED | MAP_ANONYMOUS;
return mmap(NULL, size, protection, visibility, -1, 0);
}
shmget approach:
void * my_malloc(int size)
{
void * ptr = NULL;
key_current = key_first++;
int shm_id;
if ((shm_id = shmget(key_current, size , IPC_CREAT | 0666)) < 0) {
perror("shmget error.");printf("errno= %d EINVAL=%d \n ", errno , EINVAL);
return NULL;
}
if ((ptr = shmat(shm_id, NULL, 0)) == (void *) - 1) {
perror("shmat error");
//exit(1);
return NULL;
}
current_index ++ ;
shm_id_arr[current_index] = shm_id ;
return ptr;
}
Solution 1:[1]
I solved this by creating an array with predefined number of node elements in the parent process using shared memory and initializing all of the indices before the server listens for client requests and uses fork().
#define MAX_NODES 1000
typedef struct node{
char data[1024];
} node;
node *nodes;
void init_array(){
int id;
if((id = shmget(12345, sizeof(node)*MAX_NODES , IPC_CREAT | 0666) < 0){
perror("shmget error");
}
nodes = (node*) shmat(id, NULL, 0);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saad Waseem |
