8109dfb214d3339a8734f1ee20fc25cd178b531f
[musl] / src / mq / mq_notify.c
1 #include <mqueue.h>
2 #include <pthread.h>
3 #include <errno.h>
4 #include <sys/socket.h>
5 #include <signal.h>
6 #include <unistd.h>
7 #include <semaphore.h>
8 #include "syscall.h"
9
10 struct args {
11         sem_t sem;
12         int sock;
13         mqd_t mqd;
14         int err;
15         const struct sigevent *sev;
16 };
17
18 static void *start(void *p)
19 {
20         struct args *args = p;
21         char buf[32];
22         ssize_t n;
23         int s = args->sock;
24         void (*func)(union sigval) = args->sev->sigev_notify_function;
25         union sigval val = args->sev->sigev_value;
26         struct sigevent sev2;
27         static const char zeros[32];
28         int err;
29
30         sev2.sigev_notify = SIGEV_THREAD;
31         sev2.sigev_signo = s;
32         sev2.sigev_value.sival_ptr = (void *)&zeros;
33
34         args->err = err = -__syscall(SYS_mq_notify, args->mqd, &sev2);
35         sem_post(&args->sem);
36         if (err) return 0;
37
38         pthread_detach(pthread_self());
39         n = recv(s, buf, sizeof(buf), MSG_NOSIGNAL|MSG_WAITALL);
40         close(s);
41         if (n==sizeof buf && buf[sizeof buf - 1] == 1)
42                 func(val);
43         return 0;
44 }
45
46 int mq_notify(mqd_t mqd, const struct sigevent *sev)
47 {
48         struct args args = { .sev = sev };
49         pthread_attr_t attr;
50         pthread_t td;
51         int s;
52         int cs;
53
54         if (!sev || sev->sigev_notify != SIGEV_THREAD)
55                 return syscall(SYS_mq_notify, mqd, sev);
56
57         s = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, 0);
58         if (s < 0) return -1;
59         args.sock = s;
60         args.mqd = mqd;
61
62         if (sev->sigev_notify_attributes) attr = *sev->sigev_notify_attributes;
63         else pthread_attr_init(&attr);
64         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
65         sem_init(&args.sem, 0, 0);
66
67         if (pthread_create(&td, &attr, start, &args)) {
68                 __syscall(SYS_close, s);
69                 errno = EAGAIN;
70                 return -1;
71         }
72
73         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
74         sem_wait(&args.sem);
75         sem_destroy(&args.sem);
76
77         if (args.err) {
78                 __syscall(SYS_close, s);
79                 pthread_join(td, 0);
80                 pthread_setcancelstate(cs, 0);
81                 errno = args.err;
82                 return -1;
83         }
84
85         pthread_setcancelstate(cs, 0);
86         return 0;
87 }