Linux下进程通信–消息队列

代码

/*
 * main.cc
 *
 *   Created on: 2010-1-19
 *  Description: IPC--消息队列的实现
 *    Copyright: 2010 @ ICT Li Heyuan
 */
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
	long mtype;
	char mtext[10];
} _msgbuf;

const char *path = "/tmp/test_ipc_1234";
int proj_id = 123;
int ret;

int main() {

	//第零步 创建path这个文件
	ret = creat(path, S_IRWXU);
	if (ret == -1) {
		printf("create file fail.\n");
		exit(-1);
	}

	//第一步 获得key_t(System V key)
	key_t key = ftok(path, 'd');
	if (key == -1) {
		printf("get key_t fail.\n");
		exit(-1);
	}

	//第二步 创建一个message_queue
	//这个|S_IRWXU是设置权限,同open的mode参数,最低8位决定
	int msgid = msgget(key, IPC_CREAT | S_IRWXU);
	if (msgid == -1) {
		printf("create msg_queue fail:%s.\n", strerror(errno));
		exit(-1);
	}

	ret = fork();
	if (ret == -1) {
		printf("fork fail.\n");
		exit(-1);
	} else if (ret == 0) {
		printf("I'm child pid %d\n", getpid());
		//第三步  子进程 发送msgsnd
		_msgbuf msg1;
		msg1.mtype = 4;
		strcpy(msg1.mtext, "Hi");
		ret = msgsnd(msgid, &msg1, sizeof(_msgbuf), 0);
		if (ret == -1) {
			printf("send msg fail:%s\n", strerror(errno));
		} else {
			printf("send msg success.\n");
		}

		exit(0);
	} else {
		//第四步  父进程 接受msgsnd
		printf("I'm father pid %d\n", getpid());
		_msgbuf msg1;
		ssize_t size = msgrcv(msgid, &msg1, sizeof(msg1), 4, 0);
		if (size == -1) {
			printf("rcv msg fail.\n");
		} else {
			printf("Child send me a msg %d bytes,said:%s\n", size, msg1.mtext);
		}

	}

	ret = msgctl(msgid, IPC_RMID, NULL);//删除消息队列
	if (ret == -1) {
		printf("unlink msg queue error\n");
		exit(-1);
	}

	exit(0);
}

Leave a Reply

Your email address will not be published.