5.19 消息队列(中):异步通知

1、实验代码
mq_notify.c

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

mqd_t mq_id;
char buff[8192];
struct sigevent sigev;

static void signal_hander (int signo)
{
	ssize_t receive_len;
	mq_notify (mq_id, &sigev);
	receive_len = mq_receive (mq_id, buff, 8192, NULL);
	if (receive_len == -1)
	{
		perror ("mq_receive");
		exit (EXIT_FAILURE);
	}
	printf ("read %ld bytes: %s\n",(long)receive_len, buff);
	return;
}

int main (void)
{
	mq_id = mq_open ("/notify_mqueue", O_RDONLY | O_CREAT, 0644, NULL);
	if (mq_id == -1)
	{
		perror ("mq_open");
		exit (EXIT_FAILURE);
	}

	signal (SIGUSR1, signal_hander);
	sigev.sigev_notify = SIGEV_SIGNAL;
	sigev.sigev_signo  = SIGUSR1;
	mq_notify (mq_id, &sigev);

    int count = 0;
	while (1)
    {
        printf ("while loop %d\n", count++);
        sleep (1);
    }
    mq_close (mq_id);
	return 0;
}


mq_send.c

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

int main (void)
{
	mqd_t mq_id;
	if ((mq_id = mq_open("/notify_mqueue", O_WRONLY | O_CREAT, 0644, NULL)) == -1)
	{
		perror ("mq_open");
		exit (EXIT_FAILURE);
	}

	while (1)
	{
		if (mq_send (mq_id, "hello world", sizeof("hello world"), 1) == -1)
		{
			perror ("mq_receive");
			exit (EXIT_FAILURE);
		}
		printf ("msg send success--------\n");
		sleep (2);
	}

	return 0;
}

2、实验结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值