#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h> 
#include <sys/stat.h>
#include <sys/time.h> 
#include <sys/types.h>
#include <time.h> 
#include <unistd.h>

main()
{
  struct mq_attr mqa ; 
  mqd_t mid ;
  int i ; 
  int sleeptime ; 
  char buf[50] ; 
  struct timeval curtime ; 
  struct timeval waittime ; 
  fd_set *readfds, *writefds, *exceptfds ; 

  readfds = (fd_set *)malloc(sizeof(fd_set)) ;
  FD_ZERO(readfds) ; 
  writefds = (fd_set *)malloc(sizeof(fd_set)) ;
  FD_ZERO(writefds) ; 
  exceptfds = (fd_set *)malloc(sizeof(fd_set)) ;
  FD_ZERO(exceptfds) ; 

  mqa.mq_flags = 0 ; 
  mqa.mq_maxmsg = 10 ; 
  mqa.mq_msgsize = 100 ; 
  mqa.mq_curmsgs = 0 ; 
  mid = mq_open("/foo", O_WRONLY|O_CREAT, S_IRWXU, &mqa) ; 
  for (i = 0 ; i < 50 ; i++)
  {
    sprintf(buf, "message %d", i) ; 
    mq_send(mid, buf, strlen(buf)+1, 1) ; 
    printf("just sent message <<%s>>\n", buf) ; 
    mq_getattr(mid, &mqa) ; 
    printf("producer: mq has %ld messages in it\n", mqa.mq_curmsgs) ; 

    sleeptime = random() % 0xFFFF ; 
    waittime.tv_sec = 0 ; 
    waittime.tv_usec = sleeptime ; 
#if DEBUG_LEVEL > 5     
    printf("sleeping for %d\n", sleeptime) ; 
#endif 
    
    select(0, readfds, writefds, exceptfds, &waittime) ; 

  } 
  exit(0) ; 
} 
