//server.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <sys/msg.h>
#define FILE_MSG "dm14_消息队列serverTest.c"
struct msgbuff
{
long mtype;
char buffer[1024];
};
int main()
{
key_t key;
int msgid;
int rcvbytes = 0;
struct msgbuff msg_rcvbuf;
key = ftok(FILE_MSG, '20');
if(key == -1)
{
printf("ftok error! \n");
return -1;
}
msgid = msgget(key,S_IRUSR|S_IWUSR|IPC_CREAT|IPC_EXCL);
if(msgid == -1)
{
printf("msgget error! \n");
return -1;
}
while(1)
{
rcvbytes = msgrcv(msgid, &msg_rcvbuf, sizeof(struct msgbuff), 1, 0);
if(rcvbytes == -1)
{
printf("msgrcv error! \n");
return -1;
}
printf("recv %d bytes msg from client : %s \n", rcvbytes, msg_rcvbuf.buffer);
}
return 0;
}
//client
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <sys/msg.h>
#define FILE_MSG "dm14_消息队列serverTest.c"
struct msgbuff
{
long mtype;
char buffer[1024];
};
int main()
{
struct msgbuff msg_sndbuf;
key_t key;
int msgid;
int sndbytes = 0;
key = ftok(FILE_MSG, '20');
if(key == -1)
{
printf("ftok error!\n");
return -1;
}
msgid = msgget(key, S_IRUSR|S_IWUSR);
if(msgid == -1)
{
printf("msgget error!\n");
return -1;
}
msg_sndbuf.mtype = 1;
strcpy(msg_sndbuf.buffer,"helloworld");
sndbytes = msgsnd(msgid, &msg_sndbuf, sizeof(struct msgbuff), 0);
if(sndbytes == -1)
{
printf("msgsnd error!\n");
return -1;
}
return 0;
}