linux-消息队列

//msg_send.c

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

#define TEXT_SIZE 128


/* for sender */

struct my_msg_st{
	long int my_msg_type;
	char text[TEXT_SIZE];
};

int main(){
	int running = 1;
	int msg_id;
	struct my_msg_st msg_data;
	long int msg_to_rcv_tag = 0;
	char text[TEXT_SIZE] = {0};
	/*1. establish msg queue*/
	msg_id = msgget((key_t)1234, 0666|IPC_CREAT);
	if(-1 == msg_id){
		fprintf(stderr, "[SEND] msgget failed\n"); exit(EXIT_FAILURE);	
	}
	/* 2. send msg to msg queue*/
	while(running){
		printf("Enter some text...\n");

		fgets(text, TEXT_SIZE, stdin);
		msg_data.my_msg_type = 1;
		strcpy(msg_data.text, text);
		if(msgsnd(msg_id, (void*)&msg_data, TEXT_SIZE,  0) == -1){
				fprintf(stderr, "msgsnd failed with error:%d\n", errno); exit(EXIT_FAILURE);		
		}
		printf("[SEND]:%s\n", msg_data.text);
		if(strncmp(msg_data.text, "end", 3)==0){
			running = 0;		
		}	
	}
	/*3. delete msg queue*/
	if(msgctl(msg_id, IPC_RMID, 0) ==-1){
	        fprintf(stderr, "[SEND] msgctl(IPC_RMID) failed\n");
		exit(EXIT_FAILURE);	
	}
	exit(EXIT_SUCCESS);
}

//msg_rcv.c

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

#define TEXT_SIZE 128


/* for recver */

struct my_msg_st{
	long int my_msg_type;
	char text[TEXT_SIZE];
};

int main(){
	int running = 1;
	int msg_id;
	struct my_msg_st msg_data;
	long int msg_to_rcv_tag = 0;
	/*1. establish msg queue*/
	msg_id = msgget((key_t)1234, 0666|IPC_CREAT);
	if(-1 == msg_id){
		fprintf(stderr, "[RCV]  msgget failed\n"); exit(EXIT_FAILURE);	
	}
	/* 2. recv msg from msg queue*/
	while(running){
		if(msgrcv(msg_id, (void*)&msg_data, TEXT_SIZE, msg_to_rcv_tag, 0) == -1){
				fprintf(stderr, "msgrcv failed with error:%d\n", errno); exit(EXIT_FAILURE);		
		}
		printf("[RCV]:%s\n", msg_data.text);
		if(strncmp(msg_data.text, "end", 3)==0){
			running = 0;		
		}	
	}
	/*3. delete msg queue*/
	if(msgctl(msg_id, IPC_RMID, 0) ==-1){
	        fprintf(stderr, "[RCV] msgctl(IPC_RMID) failed\n");
		exit(EXIT_FAILURE);	
	}
	exit(EXIT_SUCCESS);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值