#include "apue.h"
struct msgbuf
{
long type;
char voltage[128];
char ID[4];
};
main(){
int id;
struct msgbuf sendbuf,readbuf;
//创建共享队列
id=msgget(IPC_PRIVATE,0777);
if(id<0){
printf("fail to create share msg \n");
}else{
printf("success to create share msg id=%d\n",id);
sendbuf.type = 100;
// strcpy(sendbuf.voltage,"hello liupan");
fgets(sendbuf.voltage,128,stdin);
//发送消息 第四个参数表示以阻塞的方式写
msgsnd(id,(void *)&sendbuf,strlen(sendbuf.voltage),0);
system("ipcs -q");
//第一次读取消息
memset(readbuf.voltage,0,sizeof(readbuf.voltage));
//100表示数据类型 128表示要读取的数据的大小 第四个表示以阻塞的方式读取
//返回值 实际读取到的字节数
int re_msg_size = msgrcv(id,(void *)&readbuf,128,100,0);
printf(" at first size of read data is %d readbuf = %s \n",re_msg_size,readbuf.voltage);
//再次读取消息
memset(readbuf.voltage,0,sizeof(readbuf.voltage));
//100表示数据类型 128表示要读取的数据的大小 第四个表示以阻塞的方式读取
//返回值 实际读取到的字节数
printf(" start to read data at second \n");
system("ipcs -q");
re_msg_size = msgrcv(id,(void *)&readbuf,128,100,0); //第二次在读数据已经没有数据了 阻塞
printf(" at second size of read data is %d 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;
}
Linux--共享队列1
最新推荐文章于 2022-10-03 10:32:31 发布