重生之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 小时前
7、MySQL 慢查询排查与优化实战指南
java·服务器·数据库
vibecode5 小时前
网站服务器失去响应怎么解决?我把连接超时和读超时这两段计时拆开跑了一遍
运维·服务器
工业一体机老司机6 小时前
Docker部署工控机采集服务 Compose编排与开机自启
运维·docker·容器
迪康Defender7 小时前
终端供应链安全:应用白名单与软件正版化检测落地|终端安全治理实践
运维·服务器·网络·安全·web安全·自动化·运维开发
lzx_0027 小时前
Linux 进程(二) 深入理解进程
linux
沫璃染墨7 小时前
从零入门计算机网络系列(十二):HTTP长连接与会话管理详解——从Connection到Cookie与Session
linux·服务器·c++·tcp/ip·ubuntu·http·交互
温暖小土7 小时前
在 CentOS 上安装 Redis Stack
linux·redis·centos
GeW9 小时前
国产化替代进入深水区之后Linux 与数据库为什么必须走向重建
linux
万联WANFLOW9 小时前
异地厂区视频监控远程运维:从组网到安全的实施要点
运维·网络·安全·企业组网·sdwan
衍玊10 小时前
深入剖析 TCP/IP 网络通信原理与内核实现
服务器·网络·tcp/ip