使用无名信号量的进程之间的同步 [英] synchronization between processes using unnamed semaphores
本文介绍了使用无名信号量的进程之间的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在过程-1
我试图将数据写入到共享内存中。在过程-2
同时我读从相同的共享内存中的数据。在这种情况下,我需要这两个进程之间的同步。如果我将通过无名信号量(使用 shm_init(),mmap()的
),将它的工作或没有?
我已经写了code这样将它的工作或没有?
FD =的shm_open(shm_name,O_CREAT | O_RDWR,S_IRUSR | S_IWUSR);SEMA = MMAP(NULL,的sizeof(sem_t),PROT_READ | PROT_WRITE,MAP_SHARED,FD,0);sem_init(SEMA,1,1);
解决方案
一般的方法会奏效。请注意以下但是:
- 的
名称
参数的shm_open(3)
应以斜线开头。通/ shm_name
来代替。 (在Linux上用glibc,它没有发生斜线工作,IIRC) - 您需要调整
FD
与ftruncate(2)
,否则你会得到一个SIGBUS
当您尝试访问共享内存。每当你的mmap(2)
的文件,你必须实际存在的文件中的映射访问任何内存和POSIX共享内存对象的工作方式相同。 (在Linux上,他们实现为文件在的/ dev / shm的
,它使用一个内存中的 tmpfs的。) - 如果您打算使用信号量上的共享内存映射同步操作,那么它是多余的,以创建一个单独的共享内存映射只是信号量。让你在代替同步操作映射的一部分。
对于后者,你可以做如以下内容:
typedef结构Shared_mem {
sem_t SEM;
INT shared_data [100];
} Shared_mem;...shared_mem = MMAP(NULL,的sizeof(Shared_mem),PROT_READ | PROT_WRITE,
MAP_SHARED,FD,0);...sem_init(安培; shared_mem->扫描电镜,1,1);
In process-1
I am trying to write the data into shared memory. At the same time in process-2
I am reading the data from the same shared memory. in this case I need to provide synchronization between these two processes. if I will go through unnamed semaphores (using shm_init(),mmap()
),will it work or not?
I have written code like this will it work or not?
fd = shm_open("shm_name", O_CREAT| O_RDWR, S_IRUSR | S_IWUSR);
sema = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE,MAP_SHARED , fd, 0);
sem_init(sema, 1, 1);
解决方案
The general approach will work. Note the following however:
- The
name
argument toshm_open(3)
should start with a slash. Pass"/shm_name"
instead. (On Linux with glibc, it happens to work without the slash, IIRC.) - You need to resize
fd
with anftruncate(2)
, or you'll get aSIGBUS
when you try to access the shared memory. Whenever yoummap(2)
a file, any memory you access in the mapping must actually exist in the file, and POSIX shared memory objects work the same way. (On Linux, they're implemented as files under/dev/shm
, which uses an in-memory tmpfs.) - If you plan to use the semaphore to synchronize operations on a shared memory mapping, then it's redundant to create a separate shared memory mapping just for the semaphore. Make it a part of the mapping you're synchronizing operations on instead.
For the latter, you could do e.g. the following:
typedef struct Shared_mem {
sem_t sem;
int shared_data[100];
} Shared_mem;
...
shared_mem = mmap(NULL, sizeof(Shared_mem), PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
...
sem_init(&shared_mem->sem, 1, 1);
这篇关于使用无名信号量的进程之间的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文