在我的应用程序中,我使用共享内存进行父子进程间的IPC(在Linux和Windows上都是如此)。Linux的完整代码位于https://github.com/devendermishra/SharedMemoryTest/blob/master/shmem_linux.cpp。以下是我在Linux上读取共享内存的代码:
在这种情况下,如果一个进程长时间不写入,那么其他进程将无限等待。一种解决方案是使用
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);
以下是需要编写的代码:
//Data is in buf, pBuf is shared memory.
memcpy(buf, pBuf, sizeof(buf));
sem_post(semn);
sem_wait(sem0);
在这种情况下,如果一个进程长时间不写入,那么其他进程将无限等待。一种解决方案是使用
sem_trywait
,如果操作无法完成,则立即返回。但在这种情况下,需要有人再次调用sem_trywait
来检查它是否可以被锁定。像文件一样,是否有类似于select
或poll
的机制来检查多个信号量的状态,如果有任何一个被触发,则执行操作而不是在单个信号量上被阻塞?
select
或poll
的机制来检查多个信号量的状态?" 对于信号量没有这样的机制,因此我描述了一种替代方法。 - Mike Seymour