/* 
 * File:   main.c
 * Author: blackpanther
 *
 * Created on November 2, 2010, 4:45 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>

#include "common.h"

#define UNIQUE_SHM_KEY    312

int main(int argc, char** argv) {
    int            sem_id;
    int            shm_id;
    int           *shm_data;
    int            sem_control;
    union  semun   parameters;

    int            fork_id;

    sem_id = semget(UNIQUE_SEM_KEY, NUMBER_OF_SEMAPHORE, IPC_CREAT);
        handle(sem_id == -1,"CAMION MANAGER -> semget: ",-1);

    shm_id = shmget(UNIQUE_SHM_KEY, sizeof(int), IPC_CREAT);
        handle(shm_id == -1,"CAMION MANAGER -> shmget: ",-1);

    //Inherited by child - Incrémenteur disponible sur la mémoire partagée
    shm_data = shmat(shm_id, NULL, NO_FLAG);
        handle(shm_data == (void *)-1,"CAMION MANAGER -> shmat: ",-2);

    //Initialize the number of camion - Automatically done !
    *shm_data = 0;

    do
    {
        fork_id = fork();                      
        switch(fork_id)                       
        {                                    
            case -1:                          
                perror("fork problem : ");    
                return -3;
                break;                         
            case 0:                           
                *shm_data = *shm_data + 1;
                //printf("CAMION -> I am the truck number %d\n",*shm_data);
                if( *shm_data == MAX_LOAD)
                {
                    printf("CAMION -> I am the last one in the car park, it's my duty to say to the ferry to leave !\n");
                    parameters.val = 0;
                    sem_control = semctl(sem_id,USED_BARRIER,SETVAL,parameters);
                        handle(sem_control == -1,"CAMION -> semctl : ",-3);
                    printf("CAMION -> job done\n");
                }
                return 0;
                break;                        
            default:
                printf("CAMION MANAGER -> I have currently %d truck in the car park.\n",*shm_data);
                waitpid(fork_id,NULL,NO_FLAG);
                break;                         
        }
        sleep(2);
    }while(*shm_data < MAX_LOAD);

    printf("CAMION MANAGER -> Max load reached : %d!\n",MAX_LOAD);

    // On se détache de la mémoire
        handle(shmdt(shm_data) < 0,"CAMION MANAGER -> shmdt: ",-4);

    return (EXIT_SUCCESS);
}

