#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <iostream.h>
#include "Message.h"


// very nice unix ipc mechanics

Message::Message( int msq_key ) {
  
  msg_id = msgget( (key_t) msq_key, 0644 | IPC_CREAT );
  if( msg_id == -1 ) {
    cerr << "Can't get message queue id" << endl;
    exit(1);
  }
}


Message::~Message() {
  
  if( msgctl( msg_id, IPC_RMID, 0 ) == -1 ) {
    cerr << "Can't delete message queue" << endl;
    //exit(1);
  }
}

int Message::send( My_Message& my_msg ) {

  return msgsnd( (key_t) msg_id, (void*) &my_msg, 
		 sizeof( My_Message) - sizeof( long ), IPC_NOWAIT );
}


int Message::receive( My_Message& my_msg, long msg_type ) {

  return msgrcv( (key_t) msg_id, (void*) &my_msg, 
		 sizeof( My_Message) - sizeof( long ), 
		 msg_type, IPC_NOWAIT );
}


int Message::size() {
  
  struct msqid_ds mbuf;
  msgctl( (key_t) msg_id, IPC_STAT, &mbuf );

  return ( mbuf.msg_qnum );
}
