IPC 与 QSharedMemory 和风险,如果其中一个进程挂起

IPC with QSharedMemory and risk if one of process hang

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

而且QT没有提供任何像TryLock()这样的方法,所以无论出于何种原因,如果子进程死了,都会导致主进程出问题,有什么解决方法吗?

您可以将对 QSharedMemory.lock()/unlock() 调用的所有使用包装在一个包装器对象中,无论 return 路径是什么(抛出异常 . ..).

例如:

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
}

希望对您有所帮助