// gcc -lrt

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mqueue.h>

int main()
{
  int status;
  pid_t pid;
  char buffer[1024];
  struct mq_attr attr;
  int l=1;
  mqd_t mymq;

    /* initialize the queue attributes */
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 1024;
    attr.mq_curmsgs = 0;

  mymq = mq_open ("/dazeq", O_CREAT,0644, &attr);
  if(mymq == (mqd_t) -1)
  {
    printf("*** error creating mq\n");
    return 1;
  }

  pid = fork ();
  if (pid == 0)
  {
    // This is the child process.  Execute the shell command.

    printf("i'm a child sending messages\n");
    while(l)
    {
      printf("child: input message>");
      gets(buffer);
      l=strlen(buffer);
      mq_send (mymq, buffer, l+1, 0);
    }
    return 2;
  }
  else if (pid < 0)
  {
    //The fork failed.  Report failure.
    printf("*** fork error\n");
    return 3;	
  }
  else
  {
    // This is the parent process.  Wait for the child to complete.

    printf("receive messages from a child\n");

    while(l)
    {
      l=mq_receive (mymq, buffer, 1024,0);
      if(l)printf("father: received> %s\n", buffer);
    }
    
    waitpid (pid, &status, 0);   
    mq_close(mymq); 
    return 0;
  }

}
