#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<mqueue.h>
#include<pthread.h>
#include<signal.h>
#include<errno.h>
mqd_t mqd;
struct mq_attr attr;
struct sigevent sigev;
static void notify_thread(union sigval);
int main(int argc, char **argv)
{
if(argc != 2)
{
fprintf(stderr, "argc != 2\n");
exit(EXIT_FAILURE);
}
mqd = mq_open(argv[1], O_RDONLY | O_NONBLOCK);
mq_getattr(mqd, &attr);
sigev.sigev_notify = SIGEV_THREAD;
sigev.sigev_value.sival_ptr = NULL;
sigev.sigev_notify_function = notify_thread;
sigev.sigev_notify_attributes = NULL;
mq_notify(mqd, &sigev);
for( ; ; )
pause();
}
static void notify_thread(union sigval arg)
{
ssize_t n;
void *buffer;
printf("notify_thread started\n");
buffer = malloc(attr.mq_msgsize);
mq_notify(mqd, &sigev);
while((n = mq_receive(mqd, buffer, attr.mq_msgsize, NULL)) >= 0)
printf("read %ld bytes\n",(long)n);
if(errno != EAGAIN)
printf("mq_receive error\n");
free(buffer);
pthread_exit(0);
}
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<mqueue.h>
#include<signal.h>
#include<errno.h>
volatile sig_atomic_t mqflag;
static void sig_usr1(int);
int main(int argc, char **argv)
{
mqd_t mqd;
void *buffer;
size_t len;
struct mq_attr attr;
sigset_t newmask, oldmask, zeromask;
struct sigevent sigev;
ssize_t n;
if(argc != 2)
{
fprintf(stderr, "argc != 2\n");
exit(EXIT_FAILURE);
}
mqd = mq_open(argv[1], O_RDONLY | O_NONBLOCK);
mq_getattr(mqd, &attr);
buffer = malloc(attr.mq_msgsize);
sigemptyset(&zeromask);
sigemptyset(&newmask);
sigaddset(&newmask, SIGUSR1);
signal(SIGUSR1, sig_usr1);
sigev.sigev_notify = SIGEV_SIGNAL;
sigev.sigev_signo = SIGUSR1;
printf("sleep 10ms\n");
sleep(10);
mq_notify(mqd, &sigev);
for( ; ; )
{
sigprocmask(SIG_BLOCK, &newmask, &oldmask);
while(mqflag == 0)
sigsuspend(&zeromask);
mqflag = 0;
mq_notify(mqd, &sigev);
while((n = mq_receive(mqd, buffer, attr.mq_msgsize, NULL)) > 0)
printf("read %ld bytes\n", (long)n);
if(errno != EAGAIN)
printf("mq_receive error\n");
sigprocmask(SIG_UNBLOCK, &newmask, NULL);
}
exit(0);
}
static void sig_usr1(int signo)
{
mqflag = 1;
return;
}