# sanfrg/tp1-sistemasoperativos architecture

> Architecture diagram of the GitHub repository sanfrg/tp1-sistemasoperativos, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-19). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/sanfrg/tp1-sistemasoperativos
- Repository: https://github.com/sanfrg/tp1-sistemasoperativos

## Overview

1. **Overall shape**
   This repo implements a small multi-process game server architecture in C. The runtime is split into three executables: `master`, multiple `player` processes, and an optional `view` process. The `master` owns the game rules and turn progression; players compute moves; the view only observes and renders state.

2. **Process roles and boundaries**
   - **`master`**: authoritative coordinator, creates shared state, spawns/attaches to players and view, validates moves, advances the game, and decides when the match ends.
   - **`player`**: autonomous worker process that reads the current board/state and proposes a move.
   - **`view`**: read-only observer that renders the board plus stats/ranking from shared memory.
   These roles are cleanly separated so the UI never drives game logic, and the players never mutate authoritative state directly.

3. **Inter-process communication model**
   The game uses two IPC mechanisms with distinct purposes:
   - **Pipes + `select()`** between players and the master for move submission. This lets the master listen to many players concurrently without blocking on any single one.
   - **Shared memory** for game state dissemination to players and the view, so everyone can inspect the current board, scores, and termination flags without copying large payloads through pipes.

4. **Master control loop**
   The master’s main loop is in `src/master_loop.c` and `src/master_game.c`. It periodically waits for input using `select()`, applies a configurable delay, and processes turns in a **round-robin** order. Moves are validated sequentially, so if two players target the same cell, the first one processed wins and the other is rejected as invalid.

5. **Game-state ownership**
   The authoritative board, player positions, scores, blocked status, reward cells, and `game_over` flag live in shared memory structures defined under `include/` and implemented in `src/shm.c`, `src/shm_generic.c`, and `src/state_sync.c`. The master is the only writer of the canonical game state; players and the view are readers, except for the players’ move requests sent over pipes.

6. **Synchronization strategy**
   Shared-memory access is coordinated with semaphore-based synchronization in `src/state_sync.c`. The design follows a readers/writers pattern so that multiple readers can inspect state concurrently while the master gets exclusive write access. This is important because both the `view` and all players may read the same state at once, but only the master may publish updates.

7. **Player behavior**
   `src/player.c` and `src/player_ai.c` implement the autonomous agent. The player reads the shared state, evaluates valid neighboring moves, and scores them using local food value, future mobility, nearby reward potential, distance from rivals, and dead-end penalties. This makes player behavior deterministic in structure but still partly stochastic on ties.

8. **View subsystem**
   The rendering path is separated into `src/view.c` and `src/view_render.c`. The view does not participate in gameplay; it consumes shared state and presents a richer visualization than the master would, including board status, per-player stats, territory percentage, and final ranking. This keeps output concerns isolated from game coordination.

9. **Process lifecycle and cleanup**
   `src/master_process.c` and `src/master_args.c` handle launching, argument parsing, signal handling, and shutdown. The repository explicitly addresses cleanup of orphaned shared memory and termination of blocked players/view processes, because a match can end normally, by timeout, or due to signals such as `SIGINT`/`SIGTERM`.

10. **Important architectural constraints**
   - Uses POSIX/Linux primitives heavily: `fork`/`exec`, `pipe2`, `select`, `shm_open`, `mmap`, semaphores, signals, and `clock_gettime(CLOCK_MONOTONIC)`.
   - The build/run flow is containerized via Docker (`run.sh`, `Makefile`) to keep the environment reproducible.
   - The match rhythm is configurable with CLI flags, especially delay and timeout, which directly affect the master loop timing.

11. **What an architecture diagram should emphasize**
   Draw the master as the hub:
   - one inbound channel from each player via pipe,
   - one shared-memory region read by both players and the view,
   - synchronization semaphores around that shared state,
   - an optional view process attached read-only,
   - and the master’s validation/game-state update loop as the only write path.
   The central design idea is “authoritative master + shared read-only state + concurrent move submission.”

Main entry points: [`src/shm.c`](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/shm.c) (Shared memory), [`src/player.c`](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/player.c) (Player main), [`src/master.c`](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master.c) (Master main), [`src/state_sync.c`](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/state_sync.c) (Sync layer)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_master["Master"]
  node_master_main["Master main<br/>entry<br/>[master.c]"]
  node_master_args["CLI args<br/>config<br/>[master_args.c]"]
  node_master_process["Process mgmt<br/>lifecycle<br/>[master_process.c]"]
  node_master_loop(("Turn loop<br/>scheduler<br/>[master_loop.c]"))
  node_master_game["Game rules<br/>[master_game.c]"]
  node_master_api["Master API<br/>interface<br/>[master.h]"]
end

subgraph group_players["Players"]
  node_player_main["Player main<br/>entry<br/>[player.c]"]
  node_player_ai{{"Move AI<br/>decision<br/>[player_ai.c]"}}
  node_player_api["Player API<br/>interface<br/>[player_ai.h]"]
end

subgraph group_view["View"]
  node_view_main["View main<br/>entry<br/>[view.c]"]
  node_view_render["Render view<br/>presentation<br/>[view_render.c]"]
  node_view_api["View API<br/>interface<br/>[view.h]"]
end

subgraph group_shared["Shared state"]
  node_state_sync["Sync layer<br/>ipc-sync<br/>[state_sync.c]"]
  node_shm_core[("Shared memory<br/>ipc-shm<br/>[shm.c]")]
  node_shm_generic["Shm helpers<br/>ipc-utils<br/>[shm_generic.c]"]
  node_state_model[("Game state<br/>model<br/>[estructuras.h]")]
  node_shm_api["IPC API<br/>interface<br/>[shm.h]"]
end

node_master_main -->|"parses"| node_master_args
node_master_main -->|"starts"| node_master_process
node_master_process -->|"runs"| node_master_loop
node_master_loop -->|"validates"| node_master_game
node_master_loop -->|"reads/writes"| node_state_sync
node_master_game -->|"updates"| node_state_model
node_master_process -->|"creates"| node_shm_core
node_shm_core -->|"uses"| node_shm_generic
node_shm_core -->|"stores"| node_state_model
node_state_sync -->|"guards"| node_state_model
node_player_main -->|"chooses"| node_player_ai
node_player_main -->|"reads"| node_state_sync
node_player_main -->|"attaches"| node_shm_core
node_player_main -->|"submits move"| node_master_main
node_view_main -->|"renders"| node_view_render
node_view_main -->|"reads"| node_state_sync
node_view_main -->|"attaches"| node_shm_core
node_view_render -->|"displays"| node_state_model
node_master_api -->|"supports"| node_master_main
node_player_api -->|"supports"| node_player_ai
node_view_api -->|"supports"| node_view_render
node_shm_api -->|"supports"| node_shm_core

click node_master_main "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master.c"
click node_master_args "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_args.c"
click node_master_process "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_process.c"
click node_master_loop "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_loop.c"
click node_master_game "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_game.c"
click node_player_main "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/player.c"
click node_player_ai "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/player_ai.c"
click node_view_main "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/view.c"
click node_view_render "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/view_render.c"
click node_state_sync "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/state_sync.c"
click node_shm_core "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/shm.c"
click node_shm_generic "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/shm_generic.c"
click node_state_model "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/estructuras.h"
click node_master_api "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/master.h"
click node_player_api "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/player_ai.h"
click node_view_api "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/view.h"
click node_shm_api "https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/shm.h"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_master_main,node_master_args,node_master_process,node_master_loop,node_master_game,node_master_api toneBlue
class node_player_main,node_player_ai,node_player_api toneAmber
class node_view_main,node_view_render,node_view_api toneMint
class node_state_sync,node_shm_core,node_shm_generic,node_state_model,node_shm_api toneRose
```

## Components

### Master

Authoritative game coordinator and lifecycle manager

- [Master main](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master.c): entry · Program entry for the authoritative server process · `src/master.c`
- [CLI args](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_args.c): config · Parses delay, timeout, and match options · `src/master_args.c`
- [Process mgmt](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_process.c): lifecycle · Launches children, handles signals, and shuts down cleanly · `src/master_process.c`
- [Turn loop](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_loop.c): scheduler · Select-based round-robin loop that drives turns · `src/master_loop.c`
- [Game rules](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/master_game.c): rules · Validates moves, advances turns, and decides game end · `src/master_game.c`
- [Master API](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/master.h): interface · Master-facing interfaces used across the coordinator modules · `include/master.h`

### Players

Autonomous move-proposing workers

- [Player main](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/player.c): entry · Entry point for autonomous player processes · `src/player.c`
- [Move AI](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/player_ai.c): decision · Scores candidate moves and chooses an action · `src/player_ai.c`
- [Player API](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/player_ai.h): interface · Player-facing interfaces for AI and process logic · `include/player_ai.h`

### View

Read-only observer and renderer

- [View main](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/view.c): entry · Entry point for the optional observer process · `src/view.c`
- [Render view](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/view_render.c): presentation · Draws board, stats, and final ranking · `src/view_render.c`
- [View API](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/view.h): interface · View-facing interfaces for rendering and state access · `include/view.h`

### Shared state

State model, shared memory, and synchronization

- [Sync layer](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/state_sync.c): ipc-sync · Semaphore coordination and reader/writer access control · `src/state_sync.c`
- [Shared memory](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/shm.c): ipc-shm · Creates and manages the shared state region · `src/shm.c`
- [Shm helpers](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/src/shm_generic.c): ipc-utils · Generic shared-memory utilities and wrappers · `src/shm_generic.c`
- [Game state](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/estructuras.h): model · Board, scores, blocked status, rewards, and game_over flag · `include/estructuras.h`
- [IPC API](https://github.com/sanfrg/tp1-sistemasoperativos/blob/main/include/shm.h): interface · Shared-memory and synchronization declarations · `include/shm.h`

## Connections

- Master main → CLI args: parses · Reads runtime configuration before startup
- Master main → Process mgmt: starts · Delegates child lifecycle management
- Process mgmt → Turn loop: runs · Hands control to the turn scheduler
- Turn loop → Game rules: validates · Applies move validation and turn progression
- Turn loop → Sync layer: reads/writes · Coordinates access to shared state during turns
- Game rules → Game state: updates · Publishes authoritative board and score changes
- Process mgmt → Shared memory: creates · Sets up the shared memory region used by all processes
- Shared memory → Shm helpers: uses · Relies on common shm helpers
- Shared memory → Game state: stores · Backs the canonical game state in shared memory
- Sync layer → Game state: guards · Serializes access with reader/writer coordination
- Player main → Move AI: chooses · Delegates move selection to the scoring logic
- Player main → Sync layer: reads · Consumes shared state under synchronization
- Player main → Shared memory: attaches · Maps the shared game region
- Player main → Master main: submits move · Sends proposed moves back through pipes
- View main → Render view: renders · Turns shared state into a visual output
- View main → Sync layer: reads · Observes state without writing it
- View main → Shared memory: attaches · Maps the shared game region read-only
- Render view → Game state: displays · Uses board, stats, territory, and ranking data
- Master API → Master main: supports · Shared declarations for master modules
- Player API → Move AI: supports · Shared declarations for player decision logic
- View API → Render view: supports · Shared declarations for rendering code
- IPC API → Shared memory: supports · Shared declarations for IPC and synchronization
