带有QSharedMemory的IPC,如果其中一个进程挂起,则存在风险

时间:2017-08-24 06:21:37

标签: c++ qt qt5 ipc

我注意到如果其中一个进程挂起,QSharedmemory.Lock()将永远持续。

并且QT没有提供像TryLock()那样的任何方法,因此对于任何原因,如果childProcess死了,它将导致主进程出现问题,是否有解决方法?

1 个答案:

答案 0 :(得分:1)

你可以在包装器对象中包装所有QSharedMemory.lock()/ unlock()调用,它将确保共享内存的解锁,无论返回路径是什么(异常抛出......)。

例如:

class SharedMemoryLocker {
public:
    SharedMemoryLocker(QSharedMemory & sharedMemory):m_sharedMemoryWrapped(sharedMemory) { m_sharedMemoryWrapped.lock(); }
    ~SharedMemoryLocker() { m_sharedMemoryWrapped.unlock(); }

private:
    QSharedMemory & m_sharedMemoryWrapped;
};

使用示例是:

void f(QSharedMemory & mem) {
    {
        SharedMemoryLocker locker(mem);
        // in this scope the shared memory is locked while no exception, return .. process ends
        // exiting will unlock the shared memory
    } // QSharedMemoryLocker destructor is called here unlocking the shared memory
    // here the shared memory is unlocked
}

希望这有帮助