/*
peter.c
*/
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#define PROJID 0xff
#define LUCY 1
#define PETER 2
int main()
{
char filenm[]="msg";
int mqid;
key_t mqkey;
struct msgbuf
{
long mtype;
char mtext[256];
}msg;
int ret;
mqkey = ftok(filenm,PROJID);
if(mqkey == -1)
{
printf("ftok() error:%s\n",strerror(errno));
exit(-1);
}
mqid = msgget(mqkey,0);
if(mqid == -1)
{
perror("msgget error\n");
exit(-1);
}
while(1)
{
msgrcv(mqid,&msg,256,LUCY,0);
printf("Lucy:%s\n",msg.mtext);
printf("Peter: ");
fgets(msg.mtext,256,stdin);
if(strncmp("quit",msg.mtext,4) == 0)
{
exit(0);
}
msg.mtext[strlen(msg.mtext)-1]='\0';
msg.mtype = PETER;
msgsnd(mqid,&msg,strlen(msg.mtext)+1,0);
}
}
/*
lucy.c
*/
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define PROJID 0xff
#define LUCY 1
#define PETER 2
int mqid;
void terminate_handler(int signo)
{
msgctl(mqid,IPC_RMID,NULL);
exit(0);
}
int main()
{
char filenm[]="msg";
key_t mqkey;
struct msgbuf
{
long mtype;
char mtext[256];
}msg;
int ret;
mqkey = ftok(filenm,PROJID);
if(mqkey == -1)
{
printf("aaa ftok() error: %s\n",strerror(errno));
exit(-1);
}
mqid = msgget(mqkey,IPC_CREAT | IPC_EXCL | 0666);
if(mqid == -1)
{
perror("msgget() error\n");
exit(-1);
}
signal(SIGINT,terminate_handler);
signal(SIGTERM,terminate_handler);
while(1)
{
printf("Lucy: ");
fgets(msg.mtext,256,stdin);
if(strncmp("quit",msg.mtext,4) == 0)
{
msgctl(mqid,IPC_RMID,NULL);
exit(0);
}
msg.mtext[strlen(msg.mtext)-1]='\0';
msg.mtype = LUCY;
msgsnd(mqid,&msg,strlen(msg.mtext)+1,0);
msgrcv(mqid,&msg,256,PETER,0);
printf("Peter:%s\n",msg.mtext);
}
}