I'm implementing a server with clients program. The communication works with a shared memory. To control access to a common resource I'm using semaphores. If the client is new to the server, the server generates an id for the client. The client saves it's id and will send this id in further requests. I'm using the following code for communicating between server and a client. This solution works only for one server and one client.
server:
#include <semaphore.h>
sem_t* server = sem_open(SEM_1, O_CREAT | O_EXCL, 0600, 1);
sem_t* client = sem_open(SEM_2, O_CREAT | O_EXCL, 0600, 0);
//other stuff
while (!want_quit)
{
sem_wait(client)
//get id of client from shared memory or generate id for client
//get the command from the client via shared memory
//process command
//write result back to shared memory
sem_post(server)
}
client:
#include <semaphore.h>
sem_t* s1 = sem_open(SEM_1, 0);
sem_t* s2 = sem_open(SEM_2, 0);
do
{
//wait for the server
sem_wait(s1);
//get result from last command from shared memory
//send new request to server by writing command into shared memory
sem_post(s2);
} while (command from shm != CLOSE);
The server should work/manage more then one client. I thought I could solve this by a third semaphore, but I'm running into a deadlock issue or the client processes the result of an other client.
My solution with a third semaphore would look like the following:
server:
sem_wait(clients);
sem_wait(client);
sem_post(server);
client:
sem_wait(s1);
sem_post(clients);
sem_post(server);
How can I solve this challenge?