消息队列函数(msgget、msgctl、msgsnd、msgrcv)及其范例

发送端

点击查看代码
/**********************************************************
 * Copyright (C) 2021 Dcs Ind. All rights reserved.
 * 
 * Author        : yunfei.cao
 * Email         : **********@outlook.com
 * Create time   : 2021-10-27 21:08
 * Last modified : 2021-10-27 21:08
 * Filename      : msg_send.c
 * Description   : 
 * *******************************************************/ 
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<linux/msg.h>
#include<stdio.h>
#define MAXMSG 512
struct my_msg   //消息队列结构体
{
	long int my_msg_type;
	int i;
	char some_text[MAXMSG];
}msg;
main()
{
	int msgid;
	char buffer[BUFSIZ];
	msgid=msgget(12,0666|IPC_CREAT);  //创建消息队列
 
	while(1){
		puts("Enter some text:");
		fgets(buffer,BUFSIZ,stdin);
		msg.i++;
		printf("i=%d\n",msg.i);
		msg.my_msg_type=3;
		strcpy(msg.some_text,buffer);
		msgsnd(msgid,&msg,MAXMSG,0);   //发送数据到缓冲区
		if(strncmp(msg.some_text,"end",3)==0){   //比较输入,若为end则跳出循环
		    break;
        }
    }
	exit(0);
}

接收端

点击查看代码
/**********************************************************
 * Copyright (C) 2021 Dcs Ind. All rights reserved.
 * 
 * Author        : yunfei.cao
 * Email         : **********@outlook.com
 * Create time   : 2021-10-27 21:09
 * Last modified : 2021-10-27 21:09
 * Filename      : msg_receive.c
 * Description   : 
 * *******************************************************/ 
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<linux/msg.h>
#include<stdio.h>
 
#define MAXMSG 512
struct my_msg
{
	long int my_msg_type;
	int i;
	char some_text[MAXMSG];
}msg;
main()
{
	int msgid;
	msg.my_msg_type=3;
	msgid=msgget(12,0666|IPC_CREAT);
	while(1)
	{
		msgrcv(msgid,&msg,BUFSIZ,msg.my_msg_type,0);
		printf("You wrote:%s and i=%d\n",msg.some_text,msg.i);
		if(strncmp(msg.some_text,"end",3)==0)
			break;
	}
	msgctl(msgid,IPC_RMID,0);
	exit(0);
}