(进程间通信)linux c语言实现消息队列

发送端代码:

/***************************************************
##filename      : msggetS.c
##author        : GYZ                               
##e-mail        : [email protected]                 
##create time   : 2018-10-18 15:52:07
##last modified : 2018-10-18 16:30:21
##description   : NA                                
***************************************************/
#include                                   
#include                                  
#include                                  
#include 
#include 
#include 


#define KEY 1000                                                    

struct msg
{
	long int mtype;
	char mtext[200];
};
                                                    
int main(int argc,char *argv[])                     
{                                                   
    int ret = 0;
	int msgid = 0;
	struct msg msgtxt;

	msgid = msgget((key_t)KEY,IPC_CREAT);
	if(-1 == msgid)
	{
		perror("msgget"),exit(-1);
	}    
	strcpy(msgtxt.mtext,"hi world!");                         
	ret = msgsnd(msgid,(void *)&msgtxt,sizeof(msgtxt.mtext),0);
	if(-1 == ret)
	{
		perror("msgsnd"),exit(-1);
	}	
	return 0;                                   
}                                                   
                                                    
                                                    

接收端代码:

/***************************************************
##filename      : msggetC.c
##author        : GYZ                               
##e-mail        : [email protected]                 
##create time   : 2018-10-18 15:52:21
##last modified : 2018-10-18 16:30:58
##description   : NA                                
***************************************************/
#include                                   
#include                                  
#include                                  
#include 
#include 
#include                                                     
 
#define KEY 1000

struct msg
{
	long int mtype;	
	char mtext[256];
};
                                                   
int main(int argc,char *argv[])                     
{                                                   
	int ret = 0;
	int msgid = 0;
	struct msg msgtxt;	

	msgid = msgget((key_t)KEY,IPC_CREAT);
	if(-1 == msgid)
	{
		perror("msgget"),exit(-1);
	}                             
	ret = msgrcv(msgid,(void *)&msgtxt,sizeof(msgtxt.mtext),0,0);
	if(-1 == ret)
	{
		perror("msgrcv"),exit(-1);
	}                 
	printf("%s\n",msgtxt.mtext);
	return 0;                                   
}                                                   
                                                    
                                                    

 参考:https://blog.csdn.net/guoping16/article/details/6584024

 

你可能感兴趣的:(C和C++编程学习,进程间通信,消息队列,linux,c)