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

运行结果如图

思维导图

相关推荐
chlk12319 小时前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑19 小时前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件20 小时前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
碳基沙盒20 小时前
OpenClaw 多 Agent 配置实战指南
运维
深紫色的三北六号1 天前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash1 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI2 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行3 天前
Linux和window共享文件夹
linux
Sinclair3 天前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
木心月转码ing3 天前
WSL+Cpp开发环境配置
linux