Hi guys,
I have been trying to implement a shared circular queue between 2 processes. My structures are as follows:
typedef struct client_entry {
long shmid;
int pid;
struct client_entry *next;
struct client_entry *prev;
} client_entry_t;
typedef struct client_queue {
unsigned int num_entries;
long current_shmid;
int notify;
struct client_entry *first;
struct client_entry *last;
pthread_mutex_t region_mutex;
} client_queue_t;
This is shared between a server and a client. Server creates the shared memory (client queue), attaches it and waits for "notify" to be set.
A client process creates and attaches the shared memory (with same KEY as that of server), adds a new client (client_entry) to the queue and sets notify = 1.
On this, the server tries to access the newly created client_entry and tries to print entry->shmid.
Snippet of server
// loads shared memory at (client_queue_t *)shm
while(shm->notify != 1) {
printf("\nWaiting... %d", shm->notify);
sleep(1);
}
printf("\nGot Notification");
pthread_mutex_lock(&shm->region_mutex);
shm->notify = 0;
pthread_mutex_unlock(&shm->region_mutex);
printf("\nServer finds first SHMID as %ld", shm->first->shmid);
Snippet of client
// loads shm and creates a new_client_id
client_entry_t client;
client.shmid = new_client_id;
client.pid = 1;
pthread_mutex_lock(&shm->region_mutex);
add_to_client(shm, &client);
pthread_mutex_unlock(&shm->region_mutex);
thread_mutex_lock(&shm->region_mutex);
//shm->num_entries = 0;
shm->notify = 1;
pthread_mutex_unlock(&shm->region_mutex);
printf("\nClient finds SHMID as %ld", shm->first->shmid );
Functions used
extern void init_client(client_queue_t *client)
{
client->first = NULL;
client->last = NULL;
client->num_entries = 0;
fprintf(stderr, "\nClient queue initialized");
return;
}
extern void add_to_client(client_queue_t *client, client_entry_t *entry)
{
entry->next = NULL;
entry->prev = client->last;
if (client->first == NULL)
client->first = entry;
else
client->last->next = entry;
client->last = entry;
printf("\nAdded to client queue: FIRST at %d", client->first->shmid);
client->num_entries++;
return;
}
Now, the add_to_client function gives the correct output
Server throws a segmentation fault
Client prints a different value.
I'm totally confused and stuck here. Please help me. Thanks.