栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Linux多进程间通信——消息传递实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux多进程间通信——消息传递实现

Linux多进程间通信——消息队列实现

之前已经分享了共享内存、管道、套接字来实现多进程的通信,下面再介绍一下消息队列,后面我还会再介绍最后一个多进程的通信方式,通过信号来实现,这样多进程通信的就全部讲完了。

消息队列:消息队列通信机制属于消息传递通信机制,消息队列是内核地址空间中的内部链表。消息可以顺序地发送到队列中(队尾进入),并有几种不同的方式从队列中读取(可以从对头,队中间任何位置读取),这一点是和管道不同的,管道只能从管道头部读取数据,所以消息队列相比管道更加灵活一些。

创建消息队列的API:

key = ftok(".", 10);//身份键值,便于进程之间的识别
qid = msgget(key, IPC_CREAT|0666);//创建消息队列
msgsnd(qid, (void *)&buf, 100, 0);
msgrcv(qid, (void *)&buf, 100, 0, 0);
msgctl(qid, IPC_RMID, NULL);

有了这些接口我们就可以直接来使用消息队列完成多进程间的通信了,下面我直接给出代码:

写进程:

#include 
#include 
#include 
#include 
#include 
#include 

struct msg_buf{
	int type;
	char buf[100];
};

int main(){
	int key;
	int qid;
	struct msg_buf buf;
	key = ftok(".", 10);//身份键值
	qid = msgget(key, IPC_CREAT|0666);
	buf.type = 10;
	
	printf("向消息队列中写入数据:n");
	while(1){
		fgets(buf.buf, 100, stdin);
		if(strncmp(buf.buf, "quit", 4) == 0){
			//下面为删除创建的消息队列
			if(msgctl(qid, IPC_RMID, NULL) < 0){
				perror("msgctl failedn");
				exit(1);
			}
			else{
				printf("remove %d queue successfullyn", qid);
				exit(0);			
			}
		}
		//将数据通过消息传递出去
		if(msgsnd(qid, (void *)&buf, 100, 0) < 0){
			perror("msgsnd failedn");
			exit(-1);
		}
	}
	return 0;
}

读进程:

#include 
#include 
#include 
#include 
#include 

struct msg_buf{
	int type;
	char buf[100];
};

int main(){
	int key;
	int qid;
	struct msg_buf buf;
	key = ftok(".", 10);
	qid = msgget(key, IPC_CREAT|0666);
	printf("key : %dn qid : %dn", key, qid);
	while(1){
		if(msgrcv(qid, (void *)&buf, 100, 0, 0) < 0){
			perror("msgrcv failedn");
			exit(-1);
		}
		printf("type:%dn get:%sn", buf.type, buf.buf);
	}
	return 0;
}

下面是运行的效果:


我是河边小乌龟爬,学习嵌入式路上的一名小学生,希望大家多多交流哇。更多内容关注公众号:河边小乌龟爬。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/992390.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号