/* 
 * File:   launch_delegator.c
 * Author: blackpanther
 *
 * Created on November 2, 2010, 11:34 AM
 */

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

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

#include <string.h>

#include "shared_data.h"

#define MY_ID "DELEGATOR"

int main(int argc, char** argv) {

    int           shm_id;
    int           msg_id;
    double*       shm_data;
    MessageBuffer theMsg;
    int           msgControl;

    say(MY_ID,"");

    msg_id = msgget(UNIQUE_MSG_KEY, IPC_CREAT);
        handle(msg_id < 0,"LOGGER -> msgget: ",-1);

    theMsg.mtype	= 1;

    //Creation de la mémoire partagé pour stocker la clef secrete (double)
    shm_id = shmget(UNIQUE_SHM_KEY, sizeof(double), IPC_CREAT);
        handle(shm_id < 0,"DELEGATOR -> shmget: ",-1);

    //On s'attache à la mémoire obtenu
    shm_data = shmat(shm_id, NULL, 0);
        handle(shm_data < 0,"DELEGATOR -> shmat: ",-2);
    // On récupère la clef
    sprintf(
            &(theMsg.mtext[0]),
            "%lf",
            *shm_data);

    // On l'écrit sur la file d'attente
    msgControl	= msgsnd(
            msg_id,
            (MessageBuffer *)&theMsg,
            MAX_INPUT,
            IPC_NOWAIT);                   // Sans attendre

        handle(msgControl < 0,"DELEGATOR -> error during message sending",-6);

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

        memset(theMsg.mtext,0,MAX_INPUT);
    // Boucle pour communiquer avec le logger
    do
    {
        say(MY_ID,"Entrez votre message (50char max.): ");
        scanf("%s",&(theMsg.mtext[0]));
        // On l'écrit sur la file d'attente
        msgControl = msgsnd(
                msg_id,
                (MessageBuffer *)&theMsg,
                MAX_INPUT,
                IPC_NOWAIT);                   // Sans attendre
        handle(msgControl < 0,"DELEGATOR -> error during message sending",-6);
    }while( strcmp(theMsg.mtext,STOP_KEYWORD) );

    say(MY_ID,"successfully terminated");

    return (EXIT_SUCCESS);
}

