您好,欢迎来到纷纭教育。
搜索
您的当前位置:首页进程:消息队列

进程:消息队列

来源:纷纭教育

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

进程1:

#include <myhead.h>
//定义消息结构体
typedef struct
{
	long mtype; 	//消息类型
	char mtext[1024]; 	//消息正文
}msgbuf;

#define MSGSZ (sizeof(msgbuf) - sizeof(long))

int main(int argc, const char *argv[])
{
	//创建key值
	key_t key = ftok("./",'0');
	if(key == -1)
	{
		perror("ftok error");
		return -1;
	}

	//创建消息队列
	int msgid = msgget(key,IPC_CREAT|06);
	if( msgid == -1 )
	{
		perror("msgget error");
		return -1;
	}

	//创建2个进程
	pid_t pid = fork();

	msgbuf sbuf,rbuf;
	//当前进程用于发送消息
	if(pid > 0)
	{
		while(1)
		{
			//printf("发送消息的类型>>>");
			//scanf("%ld",&sbuf.mtype);
			//getchar(); 							//吸收回车
			sbuf.mtype = 1; 						//本进程发送消息的类型为1
			//printf("%ld\n",sbuf.mtype);
			//printf("发送消息的正文>>>");
			fgets(sbuf.mtext , MSGSZ , stdin);
			sbuf.mtext[strlen(sbuf.mtext) - 1] = '\0'; 	//将回车置为0

			msgsnd(msgid , &sbuf ,MSGSZ , 0); 	//发送消息的正文
			//printf("发送成功\n");

			if( strcmp(sbuf.mtext,"quit") == 0 ) 	//结束循环
			{
				break;
			}
		}
	}
	
	//子进程用于接收消息
	else if(pid == 0)
	{
		
		while(1)
		{
			rbuf.mtype = 2; 						//本进程接收消息的类型
			msgrcv(msgid , &rbuf , MSGSZ , rbuf.mtype ,0); 	//接收信息
			printf("张三:%s\n",rbuf.mtext);

			if(strcmp(rbuf.mtext,"quit") == 0) 	//结束循环
			{
				break;
			}
		}

		//删除消息队列
		if( msgctl(msgid,IPC_RMID,NULL) == -1)
		{
			perror("msgctl error");
			return -1;
		}

		exit(EXIT_SUCCESS); 	//退出进程
	}

	else
	{
		perror("fork error");
		return -1;
	}

	wait(NULL); 	//回收子进程资源	
	
	return 0;
}

进程2:

#include <myhead.h>
//定义消息结构体
typedef struct
{
	long mtype; 	//消息类型
	char mtext[1024]; 	//消息正文
}msgbuf;

#define MSGSZ (sizeof(msgbuf) - sizeof(long))

int main(int argc, const char *argv[])
{
	//创建key值
	key_t key = ftok("./",'0');
	if(key == -1)
	{
		perror("ftok error");
		return -1;
	}

	//创建消息队列
	int msgid = msgget(key,IPC_CREAT|06);
	if( msgid == -1 )
	{
		perror("msgget error");
		return -1;
	}

	//创建2个进程
	pid_t pid = fork();

	msgbuf sbuf,rbuf;
	//当前进程用于发送消息
	if(pid > 0)
	{
		while(1)
		{
			//printf("发送消息的类型>>>");
			//scanf("%ld",&sbuf.mtype);
			//getchar(); 							//吸收回车
			sbuf.mtype = 2; 						//本进程发送的消息类型
			//printf("%ld\n",sbuf.mtype);
			//printf("发送消息的正文>>>");
			fgets(sbuf.mtext , MSGSZ , stdin);
			sbuf.mtext[strlen(sbuf.mtext) - 1] = '\0'; 	//将回车置为0

			msgsnd(msgid , &sbuf ,MSGSZ , 0); 	//发送消息的正文
			//printf("发送成功\n");

			if( strcmp(sbuf.mtext,"quit") == 0 ) 	//结束循环
			{
				break;
			}
		}
	
	}
	
	//子进程用于接收消息
	else if(pid == 0)
	{
		while(1)
		{
			rbuf.mtype = 1;
			msgrcv(msgid , &rbuf , MSGSZ , rbuf.mtype ,0); 	//接收信息
			printf("李四:%s\n",rbuf.mtext);

			if(strcmp(rbuf.mtext,"quit") == 0) 	//结束循环
			{
				break;
			}
		}

		exit(EXIT_SUCCESS); 	//退出进程
	}

	else
	{
		perror("fork error");
		return -1;
	}

	wait(NULL); 	//回收进程资源

	return 0;
}

思维导图:

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- fenyunshixun.cn 版权所有 湘ICP备2023022495号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务