如何使用共享内存在进程之间共享信号量
我必须将 N 个客户端进程与一台服务器同步。这些进程由一个主函数分叉,我在该函数中声明了 3 个信号量。我决定使用 POSIX 信号量,但我不知道如何在这些进程之间共享它们。我认为共享内存应该可以正常工作,但我有一些问题:
- 如何在我的段中分配正确的内存空间?
- 我可以在
shmget
的size_t
字段中使用sizeof(sem_t)
来准确分配我需要的空间吗? - 有人有类似这种情况的例子吗?
I have to synchronize N client processes with one server. These processes are forked by a main function in which I declared 3 semaphores. I decided to use POSIX semaphores but I don't know how to share them between these processes. I thought that shared memory should work correctly, but I have some questions:
- How can I allocate the right space of memory in my segment?
- Can I use
sizeof(sem_t)
insize_t
field ofshmget
in order to allocate exactly the space I need? - Does anyone have some examples similar to this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可以轻松共享命名的
POSIX
信号量为您的信号量选择一个名称
在创建信号量的过程中将
sem_open
与O_CREAT
结合使用在其他进程中打开信号量
如果你坚持使用共享内存,那当然是可能的。
我还没有测试过上面的内容,所以它可能是完全疯狂的。
It's easy to share named
POSIX
semaphoresChoose a name for your semaphore
Use
sem_open
withO_CREAT
in the process that creates themOpen semaphores in the other processes
If you insist on using shared memory, it's certainly possible.
I haven't tested the above so it could be completely bonkers.
我编写了一个示例应用程序,其中父线程(生产者)生成 N 个子线程(消费者),并使用全局数组在它们之间通信数据。全局数组是循环存储器,当数据写入数组时受到保护。
头文件:
源代码:
I wrote a sample application where a parent (producer) spawns N child (consumer) threads and uses a global array to communicate data between them. The global array is a circular memory and is protected when data is written on to the array.
Header File:
Source code:
是的,我们可以在两个进程之间使用命名信号量。
我们可以打开一个文件。
其他进程可以使用这个。
Yes, we can use the named semaphore between the two processes.
We can open a file.
And other process can use this.
我真的怀疑共享内存方法是否有效。
AFAIK 信号量实际上只是一个句柄,对于打开它的进程有效。真正的信号量信息位于内核内存中。
因此,在其他进程中使用相同的句柄值是行不通的。
I really doubt if the shared memory approach would ever work.
AFAIK the semaphore is actually just a handle, valid for the process it is opened in. The real semaphore info lies in the kernel memory.
So using the same handle value in other process is not going to work.