xref: /freebsd/tests/sys/mqueue/mqtest3.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 
2 #include <sys/types.h>
3 #include <sys/select.h>
4 #include <sys/wait.h>
5 #include <err.h>
6 #include <fcntl.h>
7 #include <mqueue.h>
8 #include <signal.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 
13 #include "freebsd_test_suite/macros.h"
14 
15 #define MQNAME	"/mytstqueue3"
16 #define LOOPS	1000
17 #define PRIO	10
18 
19 static void
20 sighandler(int sig __unused)
21 {
22 	write(1, "timeout\n", 8);
23 	_exit(1);
24 }
25 
26 int
27 main(void)
28 {
29 	fd_set set;
30 	struct mq_attr attr;
31 	int status;
32 	mqd_t mq;
33 	pid_t pid;
34 
35 	PLAIN_REQUIRE_KERNEL_MODULE("mqueuefs", 0);
36 
37 	mq_unlink(MQNAME);
38 
39 	attr.mq_maxmsg  = 5;
40 	attr.mq_msgsize = 128;
41 	mq = mq_open(MQNAME, O_CREAT | O_RDWR | O_EXCL, 0666, &attr);
42 	if (mq == (mqd_t)-1)
43 		err(1, "mq_open()");
44 	status = mq_getattr(mq, &attr);
45 	if (status)
46 		err(1, "mq_getattr()");
47 
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 
56 		signal(SIGALRM, sighandler);
57 
58 		mq = mq_open(MQNAME, O_RDWR);
59 		if (mq == (mqd_t)-1)
60 			err(1, "child process: mq_open");
61 		buf = malloc(attr.mq_msgsize);
62 		for (j = 0; j < LOOPS; ++j) {
63 			FD_ZERO(&set);
64 			FD_SET(mq_getfd_np(mq), &set);
65 			alarm(3);
66 			status = select(mq_getfd_np(mq) + 1, &set, NULL,
67 			    NULL, NULL);
68 			if (status != 1)
69 				err(1, "child process: select()");
70 			status = mq_receive(mq, buf, attr.mq_msgsize, &prio);
71 			if (status == -1)
72 				err(2, "child process: mq_receive");
73 			for (i = 0; i < attr.mq_msgsize; ++i)
74 				if (buf[i] != i)
75 					err(3, "message data corrupted");
76 			if (prio != PRIO)
77 				err(4, "priority is incorrect: %d", 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 		buf = malloc(attr.mq_msgsize);
91 		for (j = 0; j < LOOPS; ++j) {
92 			for (i = 0; i < attr.mq_msgsize; ++i) {
93 				buf[i] = i;
94 			}
95 			alarm(3);
96 			FD_ZERO(&set);
97 			FD_SET(mq_getfd_np(mq), &set);
98 			status = select(mq_getfd_np(mq) + 1, NULL, &set,
99 			    NULL, NULL);
100 			if (status != 1)
101 				err(1, "select()");
102 			status = mq_send(mq, buf, attr.mq_msgsize, PRIO);
103 			if (status) {
104 				kill(pid, SIGKILL);
105 				err(2, "mq_send()");
106 			}
107 		}
108 		alarm(3);
109 		wait(&status);
110 		alarm(0);
111 	}
112 	status = mq_close(mq);
113 	if (status)
114 		err(1, "mq_close");
115 	mq_unlink(MQNAME);
116 	return (0);
117 }
118