Search code examples
clinuxprocesssignalsfork

Creating a "game" with 2 players and referee (processes) using C in Linux based system


i'm now trying to create a game for Linux based systems, in which there are three processes:

  1. Referee - Main process
  2. Blue Player - First child process
  3. Red Player - Second child process

Of course the two child processes are created using the fork() function.

Now everything is created, i'm using shared memory to store the board and some more variables that are common to the three processes.

My problem is when i'm trying to think about how am i going to implement the turn based game - i created a common boolean variable that points whether the game is still on or finished, and one that decides who's turn is it.

Now we are entering the shared part, i had paused the two child processes and sent a signal to the first child process to "wake him up", but from now on how do i keep all the three processes together and synchronized (referee wakes first processes, it finishes the turn and paused, than referee wakes the second one, and so on...)

I guess i have to keep that part in some kind of while(game_finished == FALSE) loop but from there i'm stuck.

How do i implement that game in the way i just explained? Thanks.


Solution

  • There are several alternatives, but a busy-wait is among the worst. You could consider a solution built on shared semaphores, but I would choose one based on pipes. A process will block performing a read on an open file descriptor from which no data is presently available, so that's an easy way to make the various processes wait for one another, so as to take turns.

    Just create pipes in each direction between the referee process and each player process. On each turn, each player process attempts to read one byte from the referee. It will not proceed until the referee writes something to its end of the pipe. As a bonus, the byte(s) that is written can convey additional data / instructions, so as, for instance, to distinguish between "make a play" and "game over". Of course, the same sort of synchronization works in the other direction, too.