Linux下进程通信之消息队列

read date from message: msg_r.c

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define BUFFSIZE 2050

struct my_msg
{
	long int l_msg_type;
	char sz_msg_text[BUFFSIZE];
};

int main(void)
{
	int n_run = 1;
	int n_msgid;
	struct my_msg st_msg;
	long int l_rec_type;
	
	n_msgid = msgget((key_t)1234,0666|IPC_CREAT);
	if(n_msgid==-1)
	{
		fprintf(stderr,"create msg failed: %s!\n",strerror(errno));
		exit(EXIT_FAILURE);
	}
	
	while(n_run)
	{
		if(msgrcv(n_msgid,(void*)&st_msg,BUFFSIZE,l_rec_type,0)==-1)
		{
			if(errno==EAGAIN)
			{
				printf("No data to read!\n");
				sleep(1);
			}
			else
			{
				fprintf(stderr,"receive data error: %s !\n",strerror(errno));
				exit(EXIT_FAILURE);
			}
		}
		printf("You Write data: %s",st_msg.sz_msg_text);
		if(strncmp(st_msg.sz_msg_text,"end",3)==0)
		{
			n_run=0;
		}
	}
	
	if(msgctl(n_msgid,IPC_RMID,0)==-1)
	{
			fprintf(stderr,",remove msg failed:%s\n",strerror(errno));
			exit(EXIT_FAILURE);
	}
		
	exit(EXIT_SUCCESS);
}

write data to messag: msg_w.c

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define BUFFSIZE 1024
#define MAX_TEXT 2048

struct my_msg
{
	long int l_msg_type;
	char sz_msg_text[MAX_TEXT];
};

int main(void)
{
	int n_run = 1;
	int n_msgid;
	struct my_msg st_msg;
	long int l_rec_type;
	char sz_buff[BUFFSIZE];
	
	n_msgid = msgget((key_t)1234,0666|IPC_CREAT);
	if(n_msgid==-1)
	{
		fprintf(stderr,"create msg failed: %s!\n",strerror(errno));
		exit(EXIT_FAILURE);
	}
	
	while(n_run)
	{
		printf("please input data:");
		fgets(sz_buff,BUFFSIZE,stdin);
		st_msg.l_msg_type=1;
		strcpy(st_msg.sz_msg_text,sz_buff);
		//st_msg.sz_msg_text=sz_buff;
		if(msgsnd(n_msgid,(void*)&st_msg,MAX_TEXT,0)==-1)
		{
			fprintf(stderr,"send data error: %s!\n",strerror(errno));
			exit(EXIT_FAILURE);
		}
		
		if(strncmp(st_msg.sz_msg_text,"end",3)==0)
		{
			n_run=0;
		}
	}
	exit(EXIT_SUCCESS);
}

msgsnd与msgrec在接受和发送数据类型要注意,不然变异很容易出错

1.传送的类型

2.传送和接收的数据空间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值