#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
int main()
{
key_t key = ftok(".", '1');
if (-1 == key)
{
perror("ftok");
exit(1);
}
int msgid = msgget(key, IPC_CREAT);
if (-1 == msgid)
{
perror("msgget");
exit(2);
}
int type = 0;
char buffer[1024] = {0};
while (1)
{
scanf("%d %s", &type, buffer);
struct msgbuf buf;
buf.mtype = type;
memset(buf.mtext, 0, 1024);
strcpy(buf.mtext, buffer);
if (-1 == msgsnd(msgid, &buf, sizeof(buf.mtext), 0))
{
perror("msgsnd");
}
if (0 == strcmp(buffer, "exit"))
{
break;
}
memset(buffer, 0, 1024);
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
int main()
{
key_t key = ftok(".", '1');
if (-1 == key)
{
perror("ftok");
exit(1);
}
int msgid = msgget(key, IPC_CREAT);
if (-1 == msgid)
{
perror("msgget");
exit(2);
}
int type = 0;
scanf("%d", &type);
while (1)
{
struct msgbuf buf;
int count = msgrcv(msgid, &buf, sizeof(buf.mtext), type, 0);
if (-1 == count)
{
perror("msgrecv");
exit(3);
}
printf("recv : mtype = %d mtext = %s\n", buf.mtype, buf.mtext);
if (0 == strcmp(buf.mtext, "exit"))
{
break;
}
}
msgctl(msgid, IPC_RMID, 0);
return 0;
}