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 <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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 failed\n");
				exit(1);
			}
			else{
				printf("remove %d queue successfully\n", qid);
				exit(0);			
			}
		}
		//将数据通过消息传递出去
		if(msgsnd(qid, (void *)&buf, 100, 0) < 0){
			perror("msgsnd failed\n");
			exit(-1);
		}
	}
	return 0;
}

读进程:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>

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 : %d\n qid : %d\n", key, qid);
	while(1){
		if(msgrcv(qid, (void *)&buf, 100, 0, 0) < 0){
			perror("msgrcv failed\n");
			exit(-1);
		}
		printf("type:%d\n get:%s\n", buf.type, buf.buf);
	}
	return 0;
}

下面是运行的效果:

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

猜你喜欢

转载自blog.csdn.net/zhm1949/article/details/125449689