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