//发送端
#include "apue.h"
struct msgbuf
{
long type;
char voltage[128];
char ID[4];
};
main(){
int id,key;
struct msgbuf sendbuf;
//创建key
key = ftok("./apue.h",'a');
if(key<0){
perror("fail to create key");
return -1;
}
printf("success to create key = %d\n",key);
//根据key创建共享队列
id=msgget(key,IPC_CREAT|0777);
if(id<0){
perror("fail to create share msg");
return -1;
}
printf("success to create share msg id=%d\n",id);
system("ipcs -q");
//发送消息
sendbuf.type = 100;
strcpy(sendbuf.voltage,"hello liupan");
//发送消息 第四个参数表示以阻塞的方式写
int res_msg_snd = msgsnd(id,(void *)&sendbuf,strlen(sendbuf.voltage),0);
if(res_msg_snd<0){
perror("fail to send msg");
}
printf(" success to send msg \n");
sleep(600);
//删除共享队列
printf(" start to delete share msg===\n");
int re_msg=msgctl(id,IPC_RMID,NULL);//删除创建的共享队列
if(re_msg<0)
{
perror("");
return -1;
}
printf("success to delete msg \n");
system("ipcs -q");
return 0;
}
//读取端
#include "apue.h"
struct msgbuf
{
long type;
char voltage[128];
char ID[4];
};
main(){
int id,key;
struct msgbuf readbuf;
//创建key
key = ftok("./apue.h",'a');
if(key<0){
perror("fail to create key");
return -1;
}
printf("success to create key = %d\n",key);
//根据key创建共享队列
id=msgget(key,IPC_CREAT|0777);
if(id<0){
perror("fail to create share msg");
return -1;
}
printf("success to create share msg id=%d\n",id);
system("ipcs -q");
//读取消息
memset(readbuf.voltage,0,sizeof(readbuf.voltage));
//100表示数据类型 128表示要读取的数据的大小 第四个表示以阻塞的方式读取
//返回值 实际读取到的字节数
int re_msg_size = msgrcv(id,(void *)&readbuf,128,100,0);
if(re_msg_size<0)
{
perror("fail to read data");
}
printf(" size of read datais %d at first readbuf = %s \n",re_msg_size,readbuf.voltage);
//删除共享队列
printf(" start to delete share msg===\n");
int re_msg=msgctl(id,IPC_RMID,NULL);//删除创建的共享队列
if(re_msg<0)
{
perror("");
return -1;
}
printf("success to delete msg \n");
system("ipcs -q");
return 0;
}