重生之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;
}

运行结果如图

思维导图

相关推荐
未济3 天前
linux 配置环境变量
linux
傲世仙尊3 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
_艾伦 耶格尔.3 天前
进程间通信
linux
AI职业加油站3 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
Liuqy-053 天前
Linux IO编程——静态库、动态库
linux
此冬歌咏3 天前
K8s 节点故障实战:优雅驱逐 31 秒,硬故障 331 秒,以及那个永远 Pending 的 Pod
运维·k8s
彧azz3 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅3 天前
linux(8) 软硬链接
linux·运维·服务器
Wang's Blog3 天前
Java 项目实战: 外卖平台-文件下载与ServletOutputStream回写浏览器
服务器·项目开发