当前位置: 首页 > article >正文

10-21 使用消息队列实现两个进程的相互通信

 1.使用消息队列实现两个进程的相互通信

代码:

#include <myhead.h>
#define MSGSZ (sizeof(struct msgbuf)-sizeof(long))
struct msgbuf
{
	long mtype;//消息类型
	char mtext[128];
};
//线程主程序
void *task(void*arg)
{
	int msqid=*(int*)arg;//接受主线程的消息队列号
	struct msgbuf buf;//定义msgbuf结构体类型 用于收消息
	while(1)
	{
		msgrcv(msqid,&buf,MSGSZ,2,0);//接收类型为2的消息
		printf("收到消息:%s\n",buf.mtext);
		if(strcmp(buf.mtext,"quit")==0)//输入quit退出通信
		{
			break;
		}
	}
    //删除消息队列
	if(msgctl(msqid,IPC_RMID,NULL)==-1)
	{
		perror("msgctl error");
		return NULL;
	}
	pthread_exit(NULL);//子程序退出
}
int main(int argc, const char *argv[])
{
	//创建key
	key_t key=ftok("/",'k');
	if(key==-1)
	{
		perror("ftok error");
		return -1;
	}
	//创建消息队列
	int msqid=msgget(key,IPC_CREAT|0664);
	if(msqid==-1)
	{
		perror("msgget error");
		return -1;
	}
	//创建线程
	pthread_t tid=-1;
	if(pthread_create(&tid,NULL,task,&msqid)!=0)
	{
		perror("pthread_cteate error");
		return -1;
	}

	struct msgbuf buf;
	printf("开始聊天吧!\n");
	while(1)
	{
		buf.mtype=1;//输入类型1信息,用于另一个进程的接收端
		scanf("%ld",&buf.mtype);
		fgets(buf.mtext,MSGSZ,stdin);//获取终端输入信息存入结构体
		buf.mtext[strlen(buf.mtext)-1]=0;//字符串尾端回车改为'\0'
		msgsnd(msqid,&buf,MSGSZ,0);//将字符串发送到消息队列
		printf("发送成功\n");
		if(strcmp(buf.mtext,"quit")==0)//输入quit即退出循环
		{
			break;
		}
	}
	pthread_join(tid,NULL);//回收线程
	return 0;
}

由于进程2代码和进程1一样就不粘贴上了,只需将进程2的输入信息类型改为2,接收信息类型改为1即可。

执行结果:

 2.思维导图:


http://www.kler.cn/news/359805.html

相关文章:

  • jmeter发送post请求
  • Transformer(Vit+注意力机制)
  • NCCL报错
  • 使用rust实现类似C#中的Convert数据转换类
  • Redis优劣势分析
  • 探索 Jupyter 核心:nbformat 库的神秘力量
  • 构建effet.js人脸识别交互系统的实战之路
  • 【C++刷题】力扣-#121-买卖股票的最佳时机
  • MySQL数据库从入门到精通 第1讲 基本概念
  • 训练VLM(视觉语言模型)的经验
  • 【新人系列】Python 入门(三):项目配置文件
  • 【python】OpenCV—Sort the Point Set from Top Left to Bottom Right
  • k8s 部署步骤整理(containerd)
  • 大数据-182 Elasticsearch - 原理剖析 数据结构-倒排索引、SkipList 跳表
  • 足浴店+闸机+智能衣柜+门票系统一体化管理系统解决方案——未来之窗行业应用跨平台架构
  • C#从零开始学习(GameObject实例)(unity Lab3)
  • 买横买坑不买竖, 卖点就在鼎沸处 (2700点下买入,3300点卖出)宽幅振荡
  • 【MySQL】清理二进制日志文件 binlog.000XXX 以解决 Ubuntu 系统磁盘空间耗尽的问题
  • K8S调度不平衡问题分析过程和解决方案
  • Python网络请求库requests的10个基本用法