xref: /freebsd/tests/sys/mqueue/mqtest4.c (revision 61ba55bcf70f2340f9c943c9571113b3fd8eda69)
1 
2 #include <sys/types.h>
3 #include <sys/event.h>
4 #include <sys/select.h>
5 #include <sys/wait.h>
6 #include <err.h>
7 #include <fcntl.h>
8 #include <mqueue.h>
9 #include <signal.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 
14 #include "freebsd_test_suite/macros.h"
15 
16 #define MQNAME	"/mytstqueue4"
17 #define LOOPS	1000
18 #define PRIO	10
19 
20 static void
21 sighandler(int sig __unused)
22 {
23 	write(1, "timeout\n", 8);
24 	_exit(1);
25 }
26 
27 int
28 main(void)
29 {
30 	struct kevent kev;
31 	struct mq_attr attr;
32 	mqd_t mq;
33 	int kq, status;
34 	pid_t pid;
35 
36 	PLAIN_REQUIRE_KERNEL_MODULE("mqueuefs", 0);
37 
38 	mq_unlink(MQNAME);
39 
40 	attr.mq_maxmsg  = 5;
41 	attr.mq_msgsize = 128;
42 	mq = mq_open(MQNAME, O_CREAT | O_RDWR | O_EXCL, 0666, &attr);
43 	if (mq == (mqd_t) -1)
44 		err(1, "mq_open()");
45 	status = mq_getattr(mq, &attr);
46 	if (status)
47 		err(1, "mq_getattr()");
48 	pid = fork();
49 	if (pid == 0) { /* child */
50 		char *buf;
51 		int j, i;
52 		unsigned int prio;
53 
54 		mq_close(mq);
55 		kq = kqueue();
56 		mq = mq_open(MQNAME, O_RDWR);
57 		if (mq == (mqd_t)-1)
58 			err(1, "child: mq_open");
59 		EV_SET(&kev, mq_getfd_np(mq), EVFILT_READ, EV_ADD, 0, 0, 0);
60 		status = kevent(kq, &kev, 1, NULL, 0, NULL);
61 		if (status == -1)
62 			err(1, "child: kevent");
63 		buf = malloc(attr.mq_msgsize);
64 		for (j = 0; j < LOOPS; ++j) {
65 			alarm(3);
66 			status = kevent(kq, NULL, 0, &kev, 1, NULL);
67 			if (status != 1)
68 				err(1, "child: kevent 2");
69 			status = mq_receive(mq, buf, attr.mq_msgsize, &prio);
70 			if (status == -1)
71 				err(2, "child: mq_receive");
72 			for (i = 0; i < attr.mq_msgsize; ++i)
73 				if (buf[i] != i)
74 					err(3, "child: message data corrupted");
75 			if (prio != PRIO)
76 				err(4, "child: priority is incorrect: %d",
77 					 prio);
78 		}
79 		alarm(0);
80 		free(buf);
81 		mq_close(mq);
82 		return (0);
83 	} else if (pid == -1) {
84 		err(1, "fork()");
85 	} else {
86 		char *buf;
87 		int i, j;
88 
89 		signal(SIGALRM, sighandler);
90 		kq = kqueue();
91 		EV_SET(&kev, mq_getfd_np(mq), EVFILT_WRITE, EV_ADD, 0, 0, 0);
92 		status = kevent(kq, &kev, 1, NULL, 0, NULL);
93 		if (status == -1)
94 			err(1, "kevent");
95 		buf = malloc(attr.mq_msgsize);
96 		for (j = 0; j < LOOPS; ++j) {
97 			for (i = 0; i < attr.mq_msgsize; ++i) {
98 				buf[i] = i;
99 			}
100 			alarm(3);
101 			status = kevent(kq, NULL, 0, &kev, 1, NULL);
102 			if (status != 1)
103 				err(1, "child: kevent 2");
104 			status = mq_send(mq, buf, attr.mq_msgsize, PRIO);
105 			if (status) {
106 				err(2, "mq_send()");
107 			}
108 		}
109 		free(buf);
110 		alarm(3);
111 		wait(&status);
112 		alarm(0);
113 	}
114 	status = mq_close(mq);
115 	if (status)
116 		err(1, "mq_close");
117 	mq_unlink(MQNAME);
118 	return (0);
119 }
120