本文介绍了如何使用共享内存进程之间共享信号灯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要一台服务器同步ñ客户端进程。这些过程由我宣布3信号灯main函数叉。我决定使用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:
- 如何分配的内存在我段各空间?
- 我可以使用
的sizeof(sem_t)
在为size_t
的字段shmget的
为了准确地分配给我所需要的空间? - 有没有人有类似于这种情况的例子吗?
- 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.
这篇关于如何使用共享内存进程之间共享信号灯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!