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、实验结果