#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
int main()
{
//创建Key
key_t key = ftok("./", 1);
if (key < 0)
{
perror("ftok");
return -1;
}
//创建一个消息队列
int msqid = msgget(key, IPC_CREAT | 0777);
if (msqid < 0)
{
perror("msgger");
return -1;
}
//创建消息队列内容
struct msgbuf msgpA;
msgpA.mtype = 99;
//创建消息队列内容
struct msgbuf msgpB;
msgpB.mtype = 199;
//创建进程
pid_t pid = fork();
if (pid > 0)
{
while (1)
{
printf("A请输入>>>");
bzero(msgpA.mtext, sizeof(msgpA.mtext));
fgets(msgpA.mtext, sizeof(msgpA.mtext), stdin);
msgpA.mtext[strlen(msgpA.mtext) - 1] = '\0';
if (msgsnd(msqid, &msgpA, sizeof(msgpA.mtext), 0) < 0)
{
perror("msgsnd");
return -1;
}
ssize_t res;
res = msgrcv(msqid, &msgpB, sizeof(msgpB.mtext), 199, 0);
if (res < 0)
{
perror("msgrcv");
return -1;
}
printf("进程A接收%ld字节,内容为\n%s\n", res, msgpB.mtext);
if (strcmp(msgpB.mtext, "quit") == 0)
{
break;
}
}
wait(NULL);
}
else if (0 == pid)
{
while (1)
{
ssize_t res;
res = msgrcv(msqid, &msgpA, sizeof(msgpA.mtext), 99, 0);
if (res < 0)
{
perror("msgrcv");
return -1;
}
printf("进程B接收%ld字节,内容为\n%s\n", res, msgpA.mtext);
if (strcmp(msgpA.mtext, "quit") == 0)
{
break;
}
printf("B请输入>>>");
bzero(msgpB.mtext, sizeof(msgpB.mtext));
fgets(msgpB.mtext, sizeof(msgpB.mtext), stdin);
msgpB.mtext[strlen(msgpB.mtext) - 1] = '\0';
if (msgsnd(msqid, &msgpB, sizeof(msgpB.mtext), 0) < 0)
{
perror("msgsnd");
return -1;
}
}
exit(0);
}
else
{
perror("fork");
return -1;
}
//删除消息队列
msgctl(msqid,IPC_RMID,NULL);
return 0;
}