Read / write asynchronous shared memory

In my application, I am using shared memory for IPC between parent and child (both on Linux and Windows). The complete Linux code is at https://github.com/devendermishra/SharedMemoryTest/blob/master/shmem_linux.cpp

I have the following Linux code to read from shared memory:

char buf[BUF_SIZE/4];
//pBuf is the shared memory location

sem_wait(semn);
//Wait for the parent process to write on the shared memory.
memcpy(buf, pBuf, sizeof(buf));
//Signal the parent
sem_post(sem0);

      

The following code to write:

//Data is in buf, pBuf is shared memory.
memcpy(buf, pBuf, sizeof(buf));
sem_post(semn);
sem_wait(sem0);

      

In this case, if one process does not write for a long time, the other process will wait indefinitely. One solution is to use it sem_trywait

to return immediately if the operation cannot be completed. But in this case, someone needs to call again sem_trywait

to check if it can be blocked. Like a file, is there any similar mechanism for select

or poll

for checking the status of multiple semaphores, and if anyone is signaled, do the operation rather than lock it on a single semaphore?

+3


source to share


1 answer


There is no mechanism for Posix semaphores poll

.

I would use a pipe; it is controlled by regular file descriptors, so you can wait for it with poll

, etc.



The simplest use is to pass all data through it, not shared memory. If the cost of copying data to and from kernel memory might be an issue, you can save shared memory and send one character through a pipe as a signal, effectively using it as a semaphore.

+3


source







All Articles