进程间的通信 IPC---实现消息队列(msg)

msgsend.c

#include
#include
#include
#include
#include
#include
#include

#define BUFSIZE 100

//消息结构
struct my_msgbuf{
	long int my_msg_type;
	char my_mtext[BUFSIZE];
};

/**
	消息队列的实现包括
	1.创建和打开队列
	2.添加(发送)消息
	3.读取消息
	4.控制消息队列
*/
int main(void) {
	
	int running = 1;
	int msgid;
	struct my_msgbuf my_buf;
	char buffer[BUFSIZE];
	
	/*打开(或创建)消息队列*/
	msgid = msgget(1234, 0666|IPC_CREAT);
	
	while(running) {
		printf("enter some text(by end): ");
		fgets(buffer, BUFSIZE, stdin);
		my_buf.my_msg_type = 1;
		strcpy(my_buf.my_mtext, buffer);
		
		//消息队列的发送
		if(msgsnd(msgid, &my_buf, BUFSIZE, 0) < 0) {
			fprintf(stderr, "msgsnd failed!\n");
			exit(EXIT_FAILURE);
		}
		
		if(strncmp(my_buf.my_mtext, "end", 3) == 0){
			running = 0;
		}
	}
	return 0;
}

msgreceive.c

#include
#include
#include
#include
#include
#include
#include

#define BUFSIZE 100

//消息结构
struct my_msgbuf{
	long my_msg_type;
	char my_mtext[BUFSIZE];
};

int main(void) {
	
	int running = 1;
	int msgid;
	struct my_msgbuf my_buf;
	long int msg_to_receive = 0;
	
	/*打开(或创建)消息队列*/
	msgid = msgget(1234, 0666|IPC_CREAT);
	
	msg_to_receive = 1;
	printf("等待消息的发送......\n");
	while(running) {

		//消息队列的接收
		msgrcv(msgid, &my_buf, BUFSIZE, msg_to_receive, 0);
		if(strncmp(my_buf.my_mtext, "end", 3) == 0){
			running = 0;
		}
		else {
			printf("%s", my_buf.my_mtext);
		}
		
	}
	
	//消息队列的控制
	if(msgctl(msgid, IPC_RMID, 0) == -1){
		fprintf(stderr, "msgctl failed!\n");
		exit(EXIT_FAILURE);
	}
	return 0;
}

 

你可能感兴趣的:(进程之间的通信,Socket编程)