#include "msq.h"
#include <sys/time.h>

mqd_t create_mq(const char *mq_name,long int mq_maxmsg,long int mq_msgsize)
{
  mqd_t my_mq=(mqd_t)(-1);
  struct mq_attr my_attr;
  
  my_attr.mq_flags=0;
  my_attr.mq_maxmsg=mq_maxmsg;
  my_attr.mq_msgsize=mq_msgsize;
  
  my_mq=mq_open(mq_name,O_CREAT|O_RDONLY/*|O_NONBLOCK*/,S_IRWXU|S_IRWXG|S_IRWXO,&my_attr);
  
  return my_mq;	
}


mqd_t open_mq(const char *mq_name)
{    
  return mq_open(mq_name,O_WRONLY|O_NONBLOCK,0,NULL);	
}


//timeouts is in us
ssize_t recv_mq_wait(mqd_t mq,void *msg,int size,int timeouts)
{
  struct timespec timeout;
  struct timeval  now;
  ssize_t length;

 /* if(timeouts<0)
   {
   	mq_receive(mq,(char *)msg,size,unsigned int *proip);
   }*/
  gettimeofday(&now,NULL);
  now.tv_usec+=timeouts;
  if(now.tv_usec>=1000000)
   {
     now.tv_sec+=(now.tv_usec/1000000);
     now.tv_usec=now.tv_usec%1000000;
   }
  timeout.tv_sec=now.tv_sec;
  timeout.tv_nsec= now.tv_usec*1000;
  length=mq_timedreceive(mq,(char*)msg,size,NULL,&timeout);
  return length;
}





