2 * Copyright (c) 2009, Stathis Kamperis
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
17 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
18 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
20 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
22 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
24 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 #include <unistd.h> /* fork() */
37 #define MQNAME "/tmqpc"
41 static void diep(const char *s);
45 const char msg[] = "Parent says hello";
49 /* Create a message queue for write only with default parameters. */
50 md = mq_open(MQNAME, O_CREAT | O_EXCL | O_WRONLY, 0700, NULL);
55 rv = mq_send(md, msg, sizeof(msg), /* priority */ 0);
59 /* Disassociate with message queue. */
64 /* Fork and have child read the message from parent. */
68 } else if (pid == 0) {
69 /* We are inside the child. */
70 md = mq_open(MQNAME, O_RDONLY);
72 diep("child: mq_open");
74 char msg_recvd[8192]; /* Implementation defined. */
75 rv = mq_receive(md, msg_recvd, sizeof(msg_recvd), NULL);
77 diep("child: mq_receive");
79 assert(strcmp(msg_recvd, msg) == 0);
81 /* Disassociate with message queue. */
84 diep("child: mq_close");
86 /* Remove the message queue from the system. */
87 rv = mq_unlink(MQNAME);
93 /* We are inside the parent. */
101 void diep(const char *s)
106 * Message queues' name & resources are persistent, i.e., they live
107 * even after the process dies. That's why, disassociate and destroy
108 * the queue on failure, or else we might end up with zombie queues and
109 * hit the limit of max open queues.
110 * Also, we don't care about the return value of the following calls.