user3160059
user3160059

Reputation:

Shared Memory and semaphores for (multiple) client and server game

I have to program a little game for a course in C and it has to be done with using shared-memory, semaphores and a client/server architecture which can handle multiple clients (the exact requirement for the game is 2).

The two clients need to do their turns in turns and they are represented by the very same program (no fork() involved here - both started with ./client)

The server has to create all the resources when it starts up. So my main problem is regarding the semaphores. (The shared memory and the game-logic stuff works or isn't really difficult to implement.)

To decide if the server or a client has access to the shared-memory I need one semaphore. I need a second one to decide which of the clients has access. Am I right?

So I got a hint that it could be done with assigning IDs to the clients. So the shared-memory has three additional variables like so:

struct game
{
    int id_needed, client_id, id_ready;
    ... // additional stuff that is needed for the game logic itself
};

As the server boots up I'm initializing one semaphore to be 0 and the other one to be 1. When the first client appears it checks if his ID is still 0 (it's initialized as zero)

If so, it tries this:

while(my_id == 0)
{
   if(semaphore_down(semaphore_1) == 0) // Check if I have access to shared mem
   {
       shared_memory->id_needed = 1;
       if(shared_memory->id_ready == 1)
       {
           my_id = shared_memory->client_id;
           (void) printf("DEBUGGING: My ID is %d\n", my_id);
       }
   }
}
shared_memory->id_needed = 0;

And in the server I do ...

while(1)
{
    if(shared_memory->id_needed = 1)
    {
        (void) printf("DEBUGGING: ID is needed for another client!");
        shared_memory->client_id++;
        shared_memory->id_ready = 1;
        (void) printf("DEBBUGING: Dispatched new ID: %d", shared_memory->client_id);
    }
    // If enough players, start the game ...
}

I'm really stuck here. The server just increments the ID (which is only logical), but I'm stuck as to resolve this problem.

I just want the clients to work alternately on the shared-memory and the server to check the values of the game etc.

I've never worked with semaphores before and all the documentation or examples I find do just work with one client and one server, but never multiple clients.

Please enlighten me!

Upvotes: 1

Views: 1108

Answers (1)

Anton
Anton

Reputation: 6537

I see one strange thing and two things that obviously are mistakes here

  1. I see semaphore_down but no semaphore_up in the code you showed
  2. you assign instead of comparing: if(shared_memory->id_needed = 1)
  3. even if it was a comparison, it was not right anyway since compiler was free to optimize it out. Make this variable volatile to hint compiler that variable can change outside of the serial code flow. Or better declare it atomic.

Upvotes: 2

Related Questions