#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key = ftok("/home/ubuntu/",2);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key = %#X\n",key);
int msqid = msgget(key,IPC_CREAT|0777);
if(msqid < 0)
{
perror("msgget");
return -1;
}
printf("msqid = %d\n",msqid);
struct msgbuf snd;
struct msgbuf rcv;
ssize_t res = 0;
while(1)
{
//A发送
printf("请A输入数据类型>>> ");
scanf("%ld",&snd.mtype);
getchar();
if(snd.mtype <= 0)
{
break;
}
printf("请A输入信息内容>>> ");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1] = '\0';
if(msgsnd(msqid,(void*)&snd,sizeof(snd.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
printf("发送信息成功\n");
//B接收
res = msgrcv(msqid,&rcv,sizeof(rcv.mtext),0,0);
if(res < 0)
{
perror("msgrcv");
break;
}
printf("B:%s\n",rcv.mtext);
}
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#define MSG_EXCEPT 020000
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key = ftok("/home/ubuntu/",2);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key = %#X\n",key);
int msqid = msgget(key,IPC_CREAT|0777);
if(msqid < 0)
{
perror("msgget");
return -1;
}
printf("msqid = %d\n",msqid);
struct msgbuf rcv;
struct msgbuf snd;
ssize_t res = 0;
while(1)
{
//A接收
res = msgrcv(msqid,&rcv,sizeof(rcv.mtext),0,0);
if(res < 0)
{
perror("msgrcv");
break;
}
printf("A:%s\n",rcv.mtext);
//B发送
printf("请B输入数据类型>>> ");
scanf("%ld",&snd.mtype);
getchar();
if(snd.mtype <= 0)
{
break;
}
printf("请B输入信息内容>>> ");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1] = '\0';
if(msgsnd(msqid,(void*)&snd,sizeof(snd.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
printf("发送信息成功\n");
}
system("ipcs -q");
return 0;
}