linuxC多进程通讯---POSIX消息队列之异步通知

异步通知API介绍

•函数原型:

int mq_notify(mqd_t mqdes, const struct sigevent * sevp);

•函数功能:

–当空的消息队列到来消息时给进程发送一个通知
–当执行完相关处理,通知机制结束,可以重新调用mq_notify注册

•函数参数:

–mqdes:消息队列的ID
–sevp:通知方式设置

关键结构体:sigevent

•sigev_notify
	–SIGEV_NONE:有通知时什么也不做
	–SIGEV_SIGNAL:给进程发送一个信号来通知进程
	–SIGEV_THREAD/ SIGEV_THREAD_ID

•sigev_signo:要发送的信号

struct sigevent {
	int sigev_notify; /* Notification method */
	int sigev_signo; /* Notification signal */
	union sigval sigev_value; /* Data passed with notification */
	void (*sigev_notify_function) (union sigval);/* Function used for thread notification (SIGEV_THREAD) */
	void *sigev_notify_attributes; /* Attributes for notification thread (SIGEV_THREAD) */
	pid_t sigev_notify_thread_id; /* ID of thread to signal (SIGEV_THREAD_ID) */
};

举例

异步信号处理端

#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;
}

消息发送端

#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;
}
发布了349 篇原创文章 · 获赞 6 · 访问量 9737

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/100075376
今日推荐