消息队列的具体应用

进程间通讯的方式主要包括共享内存、消息队列、管道等,笔者具体实现了提到的三种。
下面是消息队列的具体应用:

//send1.c send2、send3只是更改了信息内容(即data.mtext) 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/msg.h>

typedef struct msgdata{
	long mtype;
	char mtext[128];
}MsgData;

int main(){
	int msgid=msgget((key_t)666,0664|IPC_CREAT);
	assert(msgid!=-1);
	
	MsgData data;
	memset(&data,0,sizeof(MsgData));
	data.mtype=1;
	strcpy(data.mtext,"1111");
	
	msgsnd(msgid,&data,sizeof(MsgData),0);
	exit(0);
}
//recv.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/msg.h>

typedef struct msgdata{
	long mtype;
	char mtext[128];
}MsgData;

int main(){
	int msgid=msgget((key_t)666,0664|IPC_CREAT);
	assert(msgid!=-1);
	
	MsgData data;
	memset(&data,0,sizeof(MsgData));
	
	msgrcv(msgid,&data,sizeof(MsgData)*2,1,0);
	printf("data.type:%ld\n",data.mtype);
	printf("data.text:%s\n",data.mtext);
	
	//msgctl(msgid,IPC_RMID,NULL); 笔者选择在bash用命令手动关闭(ipcrm)
	exit(0);
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值