问题
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
nameargument 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
fdwith anftruncate(2), or you'll get aSIGBUSwhen 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);
来源:https://stackoverflow.com/questions/29225593/synchronization-between-processes-using-unnamed-semaphores