It'sPete
It'sPete

Reputation: 5221

POSIX Message Queues For Passing Data Between Pthreads

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.

Upvotes: 2

Views: 4279

Answers (2)

Roland Smith
Roland Smith

Reputation: 43533

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.

Upvotes: 3

rouzier
rouzier

Reputation: 1180

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.

Upvotes: 2

Related Questions