Quote:
Originally Posted by
Shang
I have read about different approaches and decided to use SysV shared memory for a start.
Any particular reason? It's the same thing in the end, just a lot more convoluted.
Quote:
Assuming that we don't know how many clients(c) will connect and how many games(floor(c/2)) will be started the question is how to manage this shared memory segment?
My first idea was to create an array of pointers to game_state (type, see below), which would be the argument for shmat() function and store information about all games.
I don't understand what you mean by 'argument for shmat'. Do the games inherit shared memory for the parent or not? When you fork(), shared memory is inherited, so if the parent had it the children will start off with it and not need to fool with shmat().
Pointers won't work right in shared memory. Imagine that process A allocates memory and shoves the pointer into the shared mem. Process B tries to use this pointer, but process B has a
different heap than process A. So B tries to use memory it never malloc()ed and crashes.
You have to store the
contents in the shared memory, never heap pointers. Even pointers to the shared memory might not work unless every process maps the memory in the
exact same place. You could store an array index, if the array was in shared mem too.
Quote:
But how to dynamically expand this array in case of new game start without ruining attachment?
What do you mean by 'ruining attachment'?
I know that when mmap() in a segment, pages won't actually be allocated until you use them. Just make a big enough memory segment in the first place and the OS will dynamically allocate more pages as you use them. I'm not sure sysv has this same ease and simplicity.
Quote:
How to implement reading and modification of shared memory segment in turns? (player1-mainprocess-player2-mainprocess-player1-mainprocess-player2-....)
How about, each player gets its own sem, so player 1 waits on sem 1, does its turn, posts on sem 2. Player 2 waits on sem 2, does its turn, and posts on sem 3. Player 3 waits on sem 3, does its turn, posts on sem 1.
That could be a ridiculous number of semaphores for a lot of clients, though. You could have an integer stored in shared memory of whose turn it is, and when a client is created they poll it until they're told it's their turn, then they sem_wait()/sem_post()/sem_wait()/sem_post()... I think the order would remain stable after that.
As for your game structure -- instead of a structure full of big arrays, how about a big array of structures?