重生之IOday4————多进程通信

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

s.c如下

cs 复制代码
#include<my_head.h>


struct msgbuf
{
	long mtype;   //消息类型
	char mtext[1024];  //消息正文
};

//宏定义一个消息正文的大小
#define SIZE (sizeof(struct msgbuf)-sizeof(long))

int main(int argc, const char *argv[])
{
	
	//创建一个key值
	key_t key = ftok("/",'k');
	if(key == -1)
	{
		perror("ftok error\n");
		return -1;
	}
	//创建一个消息队列
	int msqid = msgget(key,IPC_CREAT|0664);
	if(msqid == -1)
	{
		perror("msgget error");
		return -1;
	}
	printf("s.out:msqid=%d\n",msqid);

	//创建一个进程
	pid_t pid = fork();
	if(pid>0)
	{
		//父进程
		struct msgbuf buf;
		while(1)
		{
			printf("s.out父进程想要发送的消息类型:");
			scanf("%ld",&buf.mtype);
			getchar();
			printf("请输入想要发送的正文:");
			fgets(buf.mtext,SIZE,stdin);  //终端获取
			buf.mtext[strlen(buf.mtext)-1] = 0;

			if(strcmp(buf.mtext,"quit")==0)
			{
				break;
			}
			msgsnd(msqid,&buf,SIZE,0);
		}
	}
	else if(pid == 0)
	{
		//子进程
		struct msgbuf buf;
		while(1)
		{
			//接收来自r.out子进程的消息
			msgrcv(msqid,&buf,SIZE,1,0);
			printf("取出的消息为:%s\n",buf.mtext);
		}
	}



	return 0;
}

r.c如下

cs 复制代码
#include<my_head.h>

struct msgbuf
{
	long mtype;  
	char mtext[1024];
};

#define SIZE (sizeof(struct msgbuf)-sizeof(long))
int main(int argc, const char *argv[])
{
	//创建一个key值
	key_t key = ftok("/",'k');
	if(key == -1)
	{
		perror("ftok error\n");
		return -1;
	}
	//创建一个消息队列
	int msqid = msgget(key,IPC_CREAT|0664);
	if(msqid == -1)
	{
		perror("msgget error");
		return -1;
	}
	printf("r.out:msqid=%d\n",msqid);

	//创建一个进程
	pid_t pid = fork();
	if(pid>0)
	{
		struct msgbuf buf;
		while(1)
		{
			//接收来自a.out父进程的消息
			msgrcv(msqid,&buf,SIZE,1,0);
			printf("取出的消息为:%s\n",buf.mtext);
		}
	
	}
	if(pid == 0)
	{
		struct msgbuf buf;
		while(1)
		{
			printf("请输入r,out子进程想要发送的消息类型:");
			scanf("%ld",&buf.mtype);
			getchar();
			printf("请输入想要发送的正文:");
			fgets(buf.mtext,SIZE,stdin);
			buf.mtext[strlen(buf.mtext)-1] = 0;

			if(strcmp(buf.mtext,"quit") == 0)
			{
				break;
			}
			msgsnd(msqid,&buf,SIZE,0);
		}
	}	return 0;
}

运行结果如图

思维导图

相关推荐
大树8812 小时前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠12 小时前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质12 小时前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
bush412 小时前
嵌入式linux学习记录十四、术语
linux·嵌入式
载数而行52013 小时前
Linux 11 动态监控指令top
linux
小宇宙Zz13 小时前
Maven依赖冲突
java·服务器·maven
Inhand陈工13 小时前
基于台达PLC与映翰通IG502的智慧水产养殖精准投喂与远程运维解决方案
运维·人工智能·物联网·阿里云·信息与通信
酣大智14 小时前
ARP代理--工作原理
运维·网络·arp·arp代理
不会C语言的男孩14 小时前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言
shushangyun_14 小时前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化