synchronization between processes using unnamed semaphores

雨燕双飞 提交于 2020-01-04 05:55:44

问题


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);

回答1:


The general approach will work. Note the following however:

  • The name argument to shm_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 an ftruncate(2), or you'll get a SIGBUS when you try to access the shared memory. Whenever you mmap(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);


来源:https://stackoverflow.com/questions/29225593/synchronization-between-processes-using-unnamed-semaphores

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!