Reputation: 819
I'm working on OpenSuse 42.3 Leap. This is my first touch with Unix message queues and I have some basic trouble with simple opening a new queue. My original issue was I wasn't able to open two queues but after few tries I got the problem reduced to this strange behaviour:
If I compile and run this
#include<stdio.h>
#include <mqueue.h>
int main() {
// printf("Hello world!\n");
/* create queue */
char *q_name = "/myQueue";
mqd_t desc = mq_open(q_name, O_RDWR | O_CREAT);
if(desc == (mqd_t) -1)
perror("Error in mq_open");
printf("We have opened %d\n", desc);
/* close descriptor and unlink name */
if (mq_close(desc)) perror("Error in close:");
if (mq_unlink(q_name)) perror("Error in unlink:");
return 0;
}
it works great with standard output:
We have opened 3
The queue is closed correctly and I can rerun it with no error.
But if I uncomment the line
printf("Hello world!\n");
it obviously still correctly compiles but when run it outputs
Hello world!
Error in mq_open: Invalid argument
We have opened -1
Error in close:: Bad file descriptor
Error in unlink:: No such file or directory
If instead of simple 'Hello world! I try to print:
printf("Hello world! My pid = %d\n", getpid());
then instead of Invalid argument
the error
Error in mq_open: Bad address
is produced.
Any idea why this simple printf
crashes the queue opening?
Upvotes: 1
Views: 1176
Reputation: 27632
From the mq_open manual page:
If O_CREAT is specified in oflag, then two additional arguments must be supplied. [...]
You don't supply them, so you have undefined behaviour. What seems to happen is that the missing arguments are taken from somewhere in memory where they would have been, and what happens to be there is different depending on what your program did just before.
Upvotes: 1