5.18 POSIX 消息队列(上):API编程实例

1、实验代码
mq_demo.c

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <mqueue.h>

#define handle_error(msg) \
   do{perror(msg);exit(EXIT_FAILURE);}while(0)

int main (void)
{
	mqd_t mq_id;
	if ((mq_id = mq_open("/posix_msg_queue", O_RDWR | O_CREAT, 0644, NULL)) == -1)
        handle_error("mq_open");

    struct mq_attr mq_attribute;
	if (mq_getattr (mq_id, &mq_attribute) == -1)
        handle_error("mq_getattr");
	printf ("mq_flags: %ld\n", mq_attribute.mq_flags);
	printf ("mq_maxmsg: %ld\n", mq_attribute.mq_maxmsg);
	printf ("mq_msgsize: %ld\n", mq_attribute.mq_msgsize);
	printf ("mq_curmsgs: %ld\n", mq_attribute.mq_curmsgs);

	int ret_from_fork;
	ret_from_fork = fork ();
	if (ret_from_fork == 0) // child process
	{
		char msg_buf[mq_attribute.mq_msgsize];
		memset (msg_buf, 0, mq_attribute.mq_msgsize);
        int count = 0;
		while (1)
		{
			if (mq_receive (mq_id, msg_buf, mq_attribute.mq_msgsize, NULL) == -1)
                handle_error("mq_receive");
			printf ("child process received msg: %s\n", msg_buf);
			sleep (1);
            if (++count % 10 == 0)
                break;
		}
	}
	else if (ret_from_fork > 0) //parent process
	{
        int count = 0;
		while (1)
		{
			if (mq_send (mq_id, "hello world", sizeof ("hello world"), 1) == -1)
                handle_error("mq_send");
			printf ("parent process: send msg to mqueue success\n");
			sleep (1);
            if (++count % 10 == 0)
                break;
		}
	}
	else
        handle_error("fork");
    
    mq_close (mq_id);
    sleep (5);

	if (mq_unlink ("/posix_msg_queue") == -1)
        handle_error("mq_unlink");
	return 0;
}

2、执行结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值