In my application, I am using shared memory for IPC between parent and child (on both Linux and Windows). Full code for Linux is at https://github.com/devendermishra/SharedMemoryTest/blob/master/shmem_linux.cpp
I have following code on Linux to read from the 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);
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, then other process will be waiting indefinitely. One solution is to use sem_trywait
to return immediately if operation cannot be completed. But in this case, someone needs to call sem_trywait
again to check if it can be locked. Like file, is there any similar mechanism to select
or poll
to check the status of multiple semaphores and if anyone is signaled, perform the operation rather than getting blocked on a single semaphore?
There is no mechanism similar to poll
for Posix semaphores.
I'd use a pipe; it's managed by regular file descriptors, so you can wait on it with poll
etc.
The simplest use is to pass all the data through it rather than shared memory. If the cost of copying the data in and out of kernel memory is likely to be an issue, then you could keep the shared memory, and send a single character through the pipe as a signal, effectively using it as a semaphore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With