1 /* $FreeBSD$ */ 2 3 #include <sys/types.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 #define MQNAME "/mytstqueue2" 14 #define LOOPS 1000 15 #define PRIO 10 16 17 static void 18 alarmhandler(int sig __unused) 19 { 20 write(1, "timeout\n", 8); 21 _exit(1); 22 } 23 24 int 25 main(void) 26 { 27 struct mq_attr attr; 28 mqd_t mq; 29 int status; 30 pid_t pid; 31 32 mq_unlink(MQNAME); 33 34 attr.mq_maxmsg = 5; 35 attr.mq_msgsize = 128; 36 mq = mq_open(MQNAME, O_CREAT | O_RDWR | O_EXCL, 0666, &attr); 37 if (mq == (mqd_t)-1) 38 err(1, "mq_open"); 39 status = mq_getattr(mq, &attr); 40 if (status) 41 err(1, "mq_getattr"); 42 pid = fork(); 43 if (pid == 0) { /* child */ 44 char *buf; 45 int j, i; 46 unsigned int prio; 47 48 mq_close(mq); 49 50 signal(SIGALRM, alarmhandler); 51 52 mq = mq_open(MQNAME, O_RDWR); 53 if (mq == (mqd_t)-1) 54 err(1, "child: mq_open"); 55 buf = malloc(attr.mq_msgsize); 56 for (j = 0; j < LOOPS; ++j) { 57 alarm(3); 58 status = mq_receive(mq, buf, attr.mq_msgsize, &prio); 59 if (status == -1) 60 err(2, "child: mq_receive"); 61 for (i = 0; i < attr.mq_msgsize; ++i) 62 if (buf[i] != i) 63 err(3, "child: message data corrupted"); 64 if (prio != PRIO) 65 err(4, "child: priority is incorrect: %d", 66 prio); 67 } 68 alarm(0); 69 free(buf); 70 mq_close(mq); 71 return (0); 72 } else if (pid == -1) { 73 err(1, "fork()"); 74 } else { 75 char *buf; 76 int i, j; 77 78 signal(SIGALRM, alarmhandler); 79 buf = malloc(attr.mq_msgsize); 80 for (j = 0; j < LOOPS; ++j) { 81 for (i = 0; i < attr.mq_msgsize; ++i) 82 buf[i] = i; 83 alarm(3); 84 status = mq_send(mq, buf, attr.mq_msgsize, PRIO); 85 if (status) 86 err(1, "mq_send"); 87 } 88 alarm(3); 89 wait(&status); 90 alarm(0); 91 } 92 status = mq_close(mq); 93 if (status) 94 err(1, "mq_close"); 95 mq_unlink(MQNAME); 96 return (0); 97 } 98