⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 commmain.cpp

📁 一个通信模块
💻 CPP
字号:
#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include <stdio.h>#define RKEY 0x9001L /*读消息队列的KEY值*/ #define WKEY 0x9002L /*写消息队列的KEY值*/ #define MSGFLG 0666  /*消息队列访问权限*/ #define IPC_WAIT 0   /*等待方式在include文件中未定义*/ class MSGBUF{public:	long mtype; 	char mtext[2*1024]; }; int main(){	int rmsqid; /*读消息队列标识符*/ 	int wmsqid; /*写消息队列标识符*/ 	/*创建读队列,写队列*/	/*若读消息队列已存在就取得标识符,否则则创建并取得标识符*/ 	if ((rmsqid=msgget(RKEY,MSGFLG|IPC_CREAT))<0) 	{ 		printf("get read message queue failed\n"); 		exit(1); 	}		/*若写消息队列已存在则失败,若不存在则创建并取得标识符*/ 	if ((wmsqid=msgget(WKEY, MSGFLG|IPC_CREAT))<0) 	{ 		printf("get write message queue failed\n"); 		exit(2); 	}	for(int i=0; i<10; i++)	{		MSGBUF rBuf;		/*接收所有类型的消息*/ 		if (msgrcv(rmsqid,&rBuf,sizeof(MSGBUF)-sizeof(long),0L,IPC_WAIT)>=0) 		{			printf("get %ld type message from queue:%s\n", rBuf.mtype,rBuf.mtext); 			sprintf(rBuf.mtext, "I have recieved %d th msg.", i+1);			if (msgsnd(wmsqid,&rBuf,sizeof(MSGBUF)-sizeof(long), IPC_NOWAIT)==0) 				printf("send message OK\n"); 			else 			{ 				printf("send message failed\n"); 				exit(4); 			} 		}		else 		{ 			printf("get message failed\n"); 			exit(3); 		}	}	return 0;	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -