xref: /freebsd/tests/sys/mqueue/mqtest3.c (revision cdebaff820b2a4915a16cedfd511823d78aab171)
1 /* $FreeBSD$ */
2 
3 #include <sys/types.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	"/mytstqueue3"
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 	fd_set set;
31 	struct mq_attr attr;
32 	int status;
33 	mqd_t mq;
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 
49 	pid = fork();
50 	if (pid == 0) { /* child */
51 		char *buf;
52 		int j, i;
53 		unsigned int prio;
54 
55 		mq_close(mq);
56 
57 		signal(SIGALRM, sighandler);
58 
59 		mq = mq_open(MQNAME, O_RDWR);
60 		if (mq == (mqd_t)-1)
61 			err(1, "child process: mq_open");
62 		buf = malloc(attr.mq_msgsize);
63 		for (j = 0; j < LOOPS; ++j) {
64 			FD_ZERO(&set);
65 			FD_SET(mq_getfd_np(mq), &set);
66 			alarm(3);
67 			status = select(mq_getfd_np(mq) + 1, &set, NULL,
68 			    NULL, NULL);
69 			if (status != 1)
70 				err(1, "child process: select()");
71 			status = mq_receive(mq, buf, attr.mq_msgsize, &prio);
72 			if (status == -1)
73 				err(2, "child process: mq_receive");
74 			for (i = 0; i < attr.mq_msgsize; ++i)
75 				if (buf[i] != i)
76 					err(3, "message data corrupted");
77 			if (prio != PRIO)
78 				err(4, "priority is incorrect: %d", prio);
79 		}
80 		alarm(0);
81 		free(buf);
82 		mq_close(mq);
83 		return (0);
84 	} else if (pid == -1) {
85 		err(1, "fork()");
86 	} else {
87 		char *buf;
88 		int i, j;
89 
90 		signal(SIGALRM, sighandler);
91 		buf = malloc(attr.mq_msgsize);
92 		for (j = 0; j < LOOPS; ++j) {
93 			for (i = 0; i < attr.mq_msgsize; ++i) {
94 				buf[i] = i;
95 			}
96 			alarm(3);
97 			FD_ZERO(&set);
98 			FD_SET(mq_getfd_np(mq), &set);
99 			status = select(mq_getfd_np(mq) + 1, NULL, &set,
100 			    NULL, NULL);
101 			if (status != 1)
102 				err(1, "select()");
103 			status = mq_send(mq, buf, attr.mq_msgsize, PRIO);
104 			if (status) {
105 				kill(pid, SIGKILL);
106 				err(2, "mq_send()");
107 			}
108 		}
109 		alarm(3);
110 		wait(&status);
111 		alarm(0);
112 	}
113 	status = mq_close(mq);
114 	if (status)
115 		err(1, "mq_close");
116 	mq_unlink(MQNAME);
117 	return (0);
118 }
119