问题描述
我必须将 N 个客户端进程与一台服务器同步.这些进程由我声明了 3 个信号量的主函数分叉.我决定使用 POSIX 信号量,但我不知道如何在这些进程之间共享它们.我认为共享内存应该可以正常工作,但我有一些问题:
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:
- 如何在我的段中分配正确的内存空间?
- 我可以在
shmget
的size_t
字段中使用sizeof(sem_t)
来准确分配我需要的空间吗? - 有人有类似这种情况的例子吗?
- 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?
推荐答案
轻松分享命名POSIX
信号量
It's easy to share named POSIX
semaphores
为您的信号量选择一个名称
Choose a name for your semaphore
#define SNAME "/mysem"
在创建它们的过程中使用 sem_open
和 O_CREAT
sem_t *sem = sem_open(SNAME, O_CREAT, 0644, 3); /* Initial value is 3. */
在其他进程中打开信号量
Open semaphores in the other processes
sem_t *sem = sem_open(SEM_NAME, 0); /* Open a preexisting semaphore. */
如果你坚持使用共享内存,那当然是可能的.
int fd = shm_open("shmname", O_CREAT, O_RDWR);
ftruncate(fd, sizeof(sem_t));
sem_t *sem = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
sem_init(sem, 1, 1);
我还没有测试过上述内容,所以它可能完全是疯狂的.
I haven't tested the above so it could be completely bonkers.
这篇关于如何使用共享内存在进程之间共享信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!