#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define SND 100
#define RCV 101
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
//获取key值
key_t key = ftok("./", 2);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key = %#X\n", key);
//创建消息队列
int msqid = msgget(key, IPC_CREAT|0664);
if(msqid < 0)
{
perror("msgget");
return -1;
}
printf("msqid = %d\n", msqid);
struct msgbuf snd = {SND}; //发送给类型为100的消息包
struct msgbuf rcv;
ssize_t res = 0;
while(1)
{
bzero(snd.mtext, sizeof(snd.mtext));
//向消息队列中发送数据
printf("请输入>>>");
fgets(snd.mtext, sizeof(snd.mtext), stdin);
snd.mtext[strlen(snd.mtext)-1] = 0;
if(msgsnd(msqid, &snd, sizeof(snd.mtext), 0) < 0)
{
perror("msgsnd");
return -1;
}
if(strcmp(snd.mtext, "quit") == 0)
break;
memset(&rcv, 0, sizeof(rcv));
//从消息队列中读取数据
res=msgrcv(msqid, &rcv, sizeof(rcv.mtext), RCV, 0);
if(res < 0)
{
perror("msgrcv");
return -1;
}
printf("%ld : %s\n", rcv.mtype, rcv.mtext);
if(strcmp(rcv.mtext, "quit") == 0)
{
//删除消息队列
msgctl(msqid, IPC_RMID, NULL);
break;
}
}
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define SND 101
#define RCV 100
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
//获取key值
key_t key = ftok("./", 2);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key = %#X\n", key);
//创建消息队列
int msqid = msgget(key, IPC_CREAT|0664);
if(msqid < 0)
{
perror("msgget");
return -1;
}
printf("msqid = %d\n", msqid);
struct msgbuf snd = {SND}; //发送给类型为100的消息包
struct msgbuf rcv;
ssize_t res = 0;
while(1)
{
memset(&rcv, 0, sizeof(rcv));
//从消息队列中读取数据
res=msgrcv(msqid, &rcv, sizeof(rcv.mtext), RCV, 0);
if(res < 0)
{
perror("msgrcv");
return -1;
}
printf("%ld : %s\n", rcv.mtype, rcv.mtext);
if(strcmp(rcv.mtext, "quit") == 0)
{
//删除消息队列
msgctl(msqid, IPC_RMID, NULL);
break;
}
bzero(snd.mtext, sizeof(snd.mtext));
//向消息队列中发送数据
printf("请输入>>>");
fgets(snd.mtext, sizeof(snd.mtext), stdin);
snd.mtext[strlen(snd.mtext)-1] = 0;
if(msgsnd(msqid, &snd, sizeof(snd.mtext), 0) < 0)
{
perror("msgsnd");
return -1;
}
if(strcmp(snd.mtext, "quit") == 0)
break;
}
return 0;
}