/* This code  is execerpted from W. Richard Stevens's Unix Network Programming
   book and his code sample. 
*/
#include	<sys/types.h>
#include	<sys/ipc.h>
#include	<sys/msg.h>

#define	KEY	((key_t) 54321)

#define	BUFFSIZE	  128
#define	PERMS		 0666
#define MSG "HELLO"
main()
{
	register int	msqid;
	int pid, status;
	struct {
	  long	m_type;
	  char  m_text[BUFFSIZE];
	} msgbuff;


	strcpy(msgbuff.m_text, MSG);
	// create a message queue , if it's not been done.
	if ( (msqid = msgget(KEY, PERMS | IPC_CREAT)) < 0)
		printf("msgget error");
	msgbuff.m_type = 1L;

	printf("sending a message \"%s\" to the message queue\n", MSG);
	if (msgsnd(msqid, &msgbuff, BUFFSIZE, 0) < 0)
	  printf("msgsnd error");

	// spwan a child process to read from a message queue
	if ((pid = fork()) == 0) {
	  if (msgrcv(msqid, &msgbuff, BUFFSIZE, 0L, 0) != BUFFSIZE) {
	    printf("msgrcv error");
	  }
	  else {
	    printf("a child successfully reads a message \"%s\" from msg queue\n", msgbuff.m_text);
	  }
	  _exit(1);
	}

	wait(&status);

	// clean up the message queue
	if (msgctl(msqid, IPC_RMID, (struct msqid_ds *) 0) < 0)
		printf("IPC_RMID error");
	printf("It's done!\n");
	exit(0);
}
