system v消息队列demo(未编译)
#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 MSG_FILE "server.c"
#define BUFFER 255
#define PERM S_IRUSR|S_IWUSR
struct msgtype{
long mtype; /*消息类型*/
char sBuffer[BUFFER+1]; /*数据成员,可有多个*/
};
int main()
{
struct msgtype msg;
key_t key;
int msgid;
if(-1 == (key=ftok(MSG_FILE,'a')) )
{
printf("ftok error\n");
exit(1);
}
msgid = msgget(key,PERM | IPC_CREATE |IPC_EXCL);/*返回一个消息队列的id*/
if(-1 == msgid)
{
printf("msgget error\n");
exit(1);
}
while(1)
{
msgrcv(msgid,&msg,sizeof(struct msgtype),1,0);/*接受消息队列。long msgtype=1,呼应位于msgid消息队列中msgtype.mtype=1的第一个消息;msgflg = 0无消息是函数的动作,一般是0。*/
printf("some one say:%s",msg.sBuffer);
msg.mtype = 2;
msgsend(msgid,&msg,sizeof(struct msgtype),0);/*msgflg = 0*/
}
return 0;
}
int main(int argc,char **argv)
{
struct msgtype msg;
key_t key;
int msgid;
key = ftok(MSG_FILE,'a');
msgid = msgget(key,PERM);
msg.mtype = 1; /*设置1*/
strcpy(msg.sBuffer,argv[1]);
msgsend(msgid,&msg,sizeof(struct msgtype),0);
memset(&msg,0,sizeof(struct msgtype));
msgrev(msgid,&msg,sizeof(struct msgtype),2,0);/*long msgtype=2*/
printf("her say :%s",msg.sBuffer);
return 0;
}
注意颜色对应关系,
还有,该队列 程序结束后并未删除,可用ipcrm删除。