#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <signal.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>



int msg_q;

struct message {
	long mtype;
	char mtext[80];
};

void child_one(void)
{
	struct message msg;
	char buf[80];
	while(!feof(stdin)) {
		fgets(buf,80,stdin);
		msg.mtype = 1;
		strncpy(msg.mtext,buf,80);
		printf("sending %s\n",msg.mtext);
		msgsnd(msg_q,&msg,sizeof(struct message),0);
	}
}

void child_two(void)
{
	struct message msg;
	while(msgrcv(msg_q,&msg,sizeof(struct message),0,0)>0) {
		printf("%s",msg.mtext);
	}
	perror("child_two");
}

int main(int argc, char **argv)
{
	int status=0;
	pid_t c1, c2;
	struct msqid_ds msg_s;
	msg_q = msgget(IPC_PRIVATE,O_RDRW);
	if(msg_q < 0) {
		perror("error creating message queue");
		return 0;
	}
	msgctl(msg_q,IPC_SET,&msg_s);
	if((c1=fork())==0) {
		printf("forking child1.\n");
		child_one();
	}
	if((c2=fork())==0) {
		printf("forking child2.\n");
		child_two();
	}
	waitpid(c1,&status,0);
	waitpid(c2,&status,0);
	msgctl(msg_q,IPC_RMID,&msg_s);
	return 0;
}
