#include <mqueue.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <string.h>

#define MSG_SIZE 16384

void handler (int sig_num) { printf ("Received sig %d.\n", sig_num); }
    
int main (int argc, char * argv []) {
  struct mq_attr attr, old_attr;  
  struct sigevent sigevent;       
  mqd_t mqdes, mqdes2;            
  char * message = "Hello world"; 
  char buf [MSG_SIZE];            
  unsigned int prio=0, i;         
  mqdes = mq_open ("/mqueue1", O_RDWR | O_CREAT, 0664, NULL);
  mq_getattr (mqdes, &attr);
  printf ("Max number of messages on the queue ==> %ld messages.\n", attr.mq_maxmsg);
  printf ("Size of messages on the queue ==> %ld bytes.\n", attr.mq_msgsize);
  printf ("%ld messages are currently on the queue.\n", attr.mq_curmsgs);
  if (attr.mq_curmsgs != 0) {
    attr.mq_flags = O_NONBLOCK;
    mq_setattr (mqdes, &attr, &old_attr);    
    while (mq_receive (mqdes, &buf[0], MSG_SIZE, &prio) != -1) 
           printf ("Received a message with priority %d.\n", prio);
    if (errno != EAGAIN) { perror ("mq_receive()"); exit (EXIT_FAILURE); }
    mq_setattr (mqdes, &old_attr, 0); }
  signal (SIGUSR1, handler);
  sigevent.sigev_signo = SIGUSR1;
  if (mq_notify (mqdes, &sigevent) == -1) {
    if (errno == EBUSY) 
        printf ("Another process has registered for notification.\n");
        exit (EXIT_FAILURE); }
  for (i= 0; i < attr.mq_maxmsg; i++) {
       printf ("Writing a message with priority %d.\n", prio);    
       if (mq_send (mqdes, message, strlen(message)+1, prio) == -1) perror ("mq_send()"); 
       prio += 5;}
  mq_close (mqdes);
  return (0); }
  



