#include <stdio.h>
#include <xparameters.h>
#include <xuartlite_l.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct _msg {
  short i ;
  char j ;
  char j2;
} ;
struct _msg msg ;

int main() 
{
  int key = 5 ;	
  char p, i = 0 ;
  int msgid ;	
  
  int retval;
  int k;
  int errors = 0;
  /*
   * Consumer
   */
  msgid = msgget( key, 4, 1, IPC_CREAT ) ;
  if( msgid == -1 ) {
    print("Consumer:: Error - Opening Message Queue \r\n") ;
    process_exit() ;
  }
  //print("Cons:: \r\n") ; 
  while(i<4) {
    k = 0;
    // msgrecv( msgid, &msg, 4, 0, 0 ); // blocking recv
    while ((retval =  msgrecv( msgid, &msg, 4, 0, IPC_NOWAIT )) == -1) {
 // replace the last param(0) with IPC_NOWAIT for non blocking
      // keep trying until it succeeds
      k++; 
      if (k >= 256) 
        k = 0;
    }
    print("Consumer : " ) ;
    outbyte(msg.j ) ;
    print("\r\n") ;
    if (msg.i != i) {
      outbyte('C'); outbyte(msg.j); putnum(k); outbyte('\r'); outbyte('\n');
      errors |= (1 << i);
    }
    i++ ;
  }
  print("Consumer done\r\n");putnum(errors);
  msgctl( msgid, IPC_RMID, NULL ) ;
  process_exit() ;
} 

