System V 消息队列(二)—— 使用消息队列实现进程间通信

现在有两个进程,一个读进程,一个写进程。他们的职责如下:

  • 写进程:创建消息队列,同时每隔1s向消息队列写入消息,消息类型为1。
  • 读进程:每隔 1s 从消息队列中取出消息类型为 1 的消息

1、写进程实现

需要注意,msgsnd的第二个成员所使用的结构体需要自己声明,而且结构体的最后一个成员因为是数组,所以该素组也被称为“柔性数组”。

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

struct msgbuf {
	long mtype;
	char mtext[1];        // 结构体最后一个成员如果是数组,这个数组被称为柔性数组
};

int main(){
	key_t key = ftok(".", 100);
	if(key < 0){
		perror("ftok");
		return 1;
	}
	int msgid = msgget(key, IPC_CREAT | IPC_EXCL | 0644);
	if(msgid < 0)
	{
		perror("msgget");
		return 1;
	}


	size_t msgsz = 128;         // 柔性数组的大小
    // 柔性数组所在结构体要动态分配内存
	struct msgbuf* msgp = (struct msgbuf*)malloc(sizeof(struct msgbuf) + sizeof(char) * msgsz);
    // 初始化结构体成员
	msgp->mtype = 1;  // 设置消息类型
	const char* str = "hello, world!";
	strcpy(msgp->mtext, str);        // 将字符串拷贝到柔性数组里

	while(1){
		msgsnd(msgid, msgp, msgsz, 0);
		sleep(1);
	}

    free(msgp);    
    msgp = NULL;
	return 0;
}

可以在命令行输入 ipcs 来验证消息队列是否创建成功。

 

2、读进程实现

int main(){
	key_t key = ftok(".", 100);
	if(key < 0){
		perror("ftok");
		return 1;
	}
	int msgid = msgget(key, IPC_CREAT);
	if(msgid < 0)
	{
		perror("msgget");
		return 1;
	}

	struct msgbuf msgp;
	while(1){
		msgrcv(msgid, &msgp, 128, 1, 0);
		printf("%s\n", msgp.mtext);
		sleep(1);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值