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

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

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

#include "common.h"

int main(int argc, char** argv) {
    // Variable used in this program
    int            sem_id;
    int            sem_control;
    struct sembuf  buffer[1];     // Un tableau d'actions
    union  semun   parameters;

    //Fetch the semaphore
    sem_id = semget(UNIQUE_SEM_KEY, NUMBER_OF_SEMAPHORE, IPC_CREAT);
        handle(sem_id == -1,"FERRY -> semget: ",-1);

    //Define our operation : Block the sempahore (setting a positive integer to the sempahore counter)
    parameters.val = 1;
    sem_control = semctl(sem_id, USED_BARRIER, SETVAL, parameters);
        handle(sem_control == -1,"FERRY -> failed at semctl: ", -2);
        
        //DEBUG
        sem_control = semctl(sem_id, USED_BARRIER, GETVAL);
            handle(sem_control == -1,"failed at semctl: ", -2);

    printf("FERRY -> Okay, now i'm set and i wait for the car park to be full.\n");

    //Then wait for the semaphore to be free
    buffer[0].sem_num = USED_BARRIER;
    buffer[0].sem_op  = 0;                   //Operation : Wait for the semaphore to be unblock (cf. common.h)
    buffer[0].sem_flg = NO_FLAG;
    sem_control = semop(
            sem_id,                //semaphore
            buffer,                //actions
            1);                    //number of actions
        handle(sem_control == -1,"FERRY -> semop",-3);


    printf("FERRY -> Ferry is full and ready to leave ! Thanks for your patience !\n");

    return (EXIT_SUCCESS);
}

