简体   繁体   English

用于在Pthread之间传递数据的POSIX消息队列

[英]POSIX Message Queues For Passing Data Between Pthreads

I have a Linux C program where I'm passing data between threads. 我有一个Linux C程序,用于在线程之间传递数据。 I was looking into using POSIX message queues to solve this since they don't require mutexes/locks. 我一直在研究使用POSIX消息队列来解决此问题,因为它们不需要互斥锁/锁。

Looking at the mq_open() call, I have to specify permissions and the path to the queue. 查看mq_open()调用,我必须指定权限和队列的路径。 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). 在权限方面,我打算使用0600,但是我想进一步限制它以防止其他进程访问队列(我在线程之间共享数据,而不是在进程之间共享数据)。 Given that the queue is "just" a file, can I use flock() with LOCK_EX to prevent accesses from other processes? 鉴于队列“只是”一个文件,我可以将flock()与LOCK_EX一起使用来防止来自其他进程的访问吗?

Thanks in advance. 提前致谢。

Regarding your question 1 look at the implementation notes for mq_open on your system. 关于问题1 ,请查看系统上mq_open的实现说明。 At least on Linux and FreeBSD message queue names must start with a slash, but must not contain other slashes. 至少在Linux和FreeBSD上,消息队列名称必须以斜杠开头,但不得包含其他斜杠。

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. 因此,尽管消息队列的名称看起来像路径,但它可能是也可能不是文件系统中的实际inode,具体取决于实现。 According to mq_overview(7) , Linux uses a virtual filesystem for message queues, which may or may not be mounted. 根据mq_overview(7) ,Linux将虚拟文件系统用于消息队列,该队列可以挂载或不挂载。

In view of this, question 2 might be moot. 有鉴于此,问题2可能没有意义。 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. 如果实际上甚至支持对/dev/mqueue中的文件进行锁定并且是否完成了所需的操作,则必须运行测试或检查内核源。

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. 另外,我不确定flock是否可以在队列描述符上使用。

Running your service as it's own user will keep other processes from being able to access the queue with mode 0600 of course. 当然,以自己的用户身份运行服务将使其他进程无法使用模式0600访问队列。

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. 您可以使用pid锁定或d-bus来这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM