• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "syscall.h"
8 #include "pthread_impl.h"
9 
10 struct args {
11 	pthread_barrier_t barrier;
12 	int sock;
13 	const struct sigevent *sev;
14 };
15 
start(void * p)16 static void *start(void *p)
17 {
18 	struct args *args = p;
19 	char buf[32];
20 	ssize_t n;
21 	int s = args->sock;
22 	void (*func)(union sigval) = args->sev->sigev_notify_function;
23 	union sigval val = args->sev->sigev_value;
24 
25 	pthread_barrier_wait(&args->barrier);
26 	n = recv(s, buf, sizeof(buf), MSG_NOSIGNAL|MSG_WAITALL);
27 	close(s);
28 	if (n==sizeof buf && buf[sizeof buf - 1] == 1)
29 		func(val);
30 	return 0;
31 }
32 
mq_notify(mqd_t mqd,const struct sigevent * sev)33 int mq_notify(mqd_t mqd, const struct sigevent *sev)
34 {
35 	struct args args = { .sev = sev };
36 	pthread_attr_t attr;
37 	pthread_t td;
38 	int s;
39 	struct sigevent sev2;
40 	static const char zeros[32];
41 
42 	if (!sev || sev->sigev_notify != SIGEV_THREAD)
43 		return syscall(SYS_mq_notify, mqd, sev);
44 
45 	s = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, 0);
46 	if (s < 0) return -1;
47 	args.sock = s;
48 
49 	if (sev->sigev_notify_attributes) attr = *sev->sigev_notify_attributes;
50 	else pthread_attr_init(&attr);
51 	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
52 	pthread_barrier_init(&args.barrier, 0, 2);
53 
54 	if (pthread_create(&td, &attr, start, &args)) {
55 		__syscall(SYS_close, s);
56 		errno = EAGAIN;
57 		return -1;
58 	}
59 
60 	pthread_barrier_wait(&args.barrier);
61 	pthread_barrier_destroy(&args.barrier);
62 
63 	sev2.sigev_notify = SIGEV_THREAD;
64 	sev2.sigev_signo = s;
65 	sev2.sigev_value.sival_ptr = (void *)&zeros;
66 
67 	if (syscall(SYS_mq_notify, mqd, &sev2) < 0) {
68 #ifdef FEATURE_PTHREAD_CANCEL
69 		pthread_cancel(td);
70 #else
71 		__syscall(SYS_tkill, td->tid, SIGCANCEL);
72 #endif
73 		__syscall(SYS_close, s);
74 		return -1;
75 	}
76 
77 	return 0;
78 }
79