2
votes

I have a Linux C program where I'm passing data between threads. I was looking into using POSIX message queues to solve this since they don't require mutexes/locks.

Looking at the mq_open() call, I have to specify permissions and the path to the queue. This leads me to two questions.

  1. Is there a well known convention for specifying the filepath? I was just going to dump the queues in the same folder as the executable.
  2. In terms of permissions, I was going to use 0600, but I want to restrict this even further to prevent other processes from accessing the queues (I'm sharing data between threads and not processes). Given that the queue is "just" a file, can I use flock() with LOCK_EX to prevent accesses from other processes?

Thanks in advance.

2
Since you are using threads, they share the same address space. (Which is kind of the whole point of using threads.) Why not use e.g. a block of memory or a linked list protected by a mutex to exchange data? - Roland Smith
There's a good deal of producer-consumer going on in a FIFO manner. So while, yes, I can create a FIFO buffer and manage it with a mutex, I feel like a good chunk of that functionality is already available in message queues. - It'sPete

2 Answers

3
votes

Regarding your question 1 look at the implementation notes for mq_open on your system. At least on Linux and FreeBSD message queue names must start with a slash, but must not contain other slashes.

So while the name of a message queue looks like a path, it might or might not be an actual inode in a filesystem, depending on the implementation. According to mq_overview(7), Linux uses a virtual filesystem for message queues, which may or may not be mounted.

In view of this, question 2 might be moot. You'd have to run a test or check the kernel source if locking of a file in /dev/mqueue is actually even supported and if it accomplishes what you want.

2
votes

I would not bother protecting the queue from outside processes.

Since flock is only advisory not mandatory it will not do you any good. Also I not sure that flock will even work on queue descriptors.

Running your service as it's own user will keep other processes from being able to access the queue with mode 0600 of course.

I would however ensure on startup only one service can work on a queue at a time. You could use pid locking or d-bus to do so.