Linux--共享队列2

//发送端
#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;
	
	
} 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值