supervisor.c 2.19 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/**
 * @file supervisor.c
 * @author Ivaylo Ivanov 11777707
 * @date 11.01.2018
 *
 * @brief Supervisor program module.
 *
 * The supervisor sets up the shared memory and the semaphores and initializes the circular buffer required
 * for the communication with the generators. It then waits for the generators to write solutions to the
 * circular buffer.
 * The supervisor program takes no arguments.
 * Once initialization is complete, the supervisor reads the solutions from the circular buffer and remembers the best solution so far, i.e. the solution with the least edges. Every time a better solution than the
 * previous best solution is found, the supervisor writes the new solution to standard output. If a generator
 * writes a solution with 0 edges to the circular buffer, then the graph is acyclic and the supervisor terminates. Otherwise the supervisor keeps reading results from the circular buffer until it receives a SIGINT
 * or a SIGTERM signal.
 * Before terminating, the supervisor notifies all generators that they should terminate as well. This can
 * be done by setting a variable in the shared memory, which is checked by the generator processes before
 * writing to the buffer. The supervisor then unlinks all shared resources and exits.
 *
 *   SYNOPSIS
 *   supervisor
 *
 **/
#include "shared/shm.c"
25 26
#include "shared/sem.c"
#include "shared/structs.c"
27 28 29 30 31 32 33

int main(int argc, char *argv[]) {
    if(argc > 1) {
        fprintf(stderr, "ERROR: Command takes no arguments");
        exit(EXIT_FAILURE);
    }

34 35
    /// Open shared memory objects
    int buffer_shmfd = create_shmfd(BUFFER_SHM_NAME);
36
    truncate_shm(buffer_shmfd, BUFF_SIZE);
37
    circ_buffer = (buffer_t *)open_shm(buffer_shmfd, sizeof(buffer_t));
38

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    /// Open semaphores
    free_sem = open_sem(FREE_SEM_NAME, BUFF_SIZE);
    used_sem = open_sem(USED_SEM_NAME, 0);
    mutex = open_sem(MUTEX_NAME, 1);


    /// Close and destory semaphores
    close_sem(free_sem);
    close_sem(used_sem);
    close_sem(mutex);

    destroy_sem(FREE_SEM_NAME);
    destroy_sem(USED_SEM_NAME);
    destroy_sem(MUTEX_NAME);

    /// Close and destroy shared memory objects
    close_shm(circ_buffer, sizeof(buffer_t));
    destroy_shm(BUFFER_SHM_NAME, buffer_shmfd);
57
}