int msgid = msgget(key,IPC_CREAT|O_WRONLY|0777);
if(msgid<0)
{
perror("msgget error!");
exit(-1);
}
Msg m;
puts("please input your type name age:");
scanf("%ld%s%d",&m.type,m.name,&m.age);
msgsnd(msgid,&m,sizeof(m)-sizeof(m.type),0);
return 0;
}
--- rcv.c ---
#include "my.h"
typedef struct{
long type;
char name[20];
int age;
}Msg;
int main()
{
key_t key = ftok("/home",'a');
printf("key:%x\n",key);
int msgid = msgget(key,O_RDONLY);
if(msgid<0)
{
perror("msgget error!");
exit(-1);
}
Msg rcv;
long type;
puts("please input type you want!");
scanf("%ld",&type);
msgrcv(msgid,&rcv,sizeof(rcv)-sizeof(type),type,0);
printf("rcv--name:%s age:%d\n",rcv.name,rcv.age);
msgctl(msgid,IPC_RMID,NULL);
return 0;
}
运行演示如下图:
总结:主要介绍了进程间通信的消息队列。