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

运行结果如图

思维导图

相关推荐
zz-zjx10 小时前
shell编程从0基础--进阶 1
linux·运维·前端·chrome·bash
咕噜签名分发冰淇淋10 小时前
搭建APP应用程序如何选择服务器
运维·服务器
吗喽对你问好11 小时前
场景题:如果一个大型项目,某一个时间所有的CPU的已经被占用了,导致服务不可用,我们开发人员应该如何使服务器尽快恢复正常
java·linux·运维·服务器
pwj去战斗吧11 小时前
Jenkins Pipeline 语法
运维·jenkins
我的xiaodoujiao11 小时前
虚拟机详细图文教程系列14、Linux虚拟机Centos8系统下载安装Python-Pycharm
linux·python·测试工具·pycharm
缘来小哥11 小时前
【Cygwin】不用装Linux系统,使用Cygwin让Windows秒变类Unix工作台
linux·后端
伞啊伞11 小时前
shell中命令小工具:cut、sort、uniq,tr的使用方式
linux·运维
何故染尘優11 小时前
限流、降级、熔断的区别和应用场景
java·服务器·网络
摩尔元数11 小时前
产线自动化效率上不去?打破设备和平台的“数据孤岛”是关键!
运维·低代码·自动化·制造·mes