QSharedMemory#

The QSharedMemory class provides access to a shared memory segment. More

Inheritance diagram of PySide6.QtCore.QSharedMemory

Synopsis#

Functions#

Note

This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE

Detailed Description#

QSharedMemory provides access to a shared memory segment by multiple threads and processes. It also provides a way for a single thread or process to lock the memory for exclusive access.

When using this class, be aware of the following platform differences:

  • Windows: QSharedMemory does not “own” the shared memory segment. When all threads or processes that have an instance of QSharedMemory attached to a particular shared memory segment have either destroyed their instance of QSharedMemory or exited, the Windows kernel releases the shared memory segment automatically.

  • Unix: QSharedMemory “owns” the shared memory segment. When the last thread or process that has an instance of QSharedMemory attached to a particular shared memory segment detaches from the segment by destroying its instance of QSharedMemory , the destructor releases the shared memory segment. But if that last thread or process crashes without running the QSharedMemory destructor, the shared memory segment survives the crash.

  • Unix: QSharedMemory can be implemented by one of two different backends, selected at Qt build time: System V or POSIX. Qt defaults to using the System V API if it is available, and POSIX if not. These two backends do not interoperate, so two applications must ensure they use the same one, even if the native key (see setNativeKey() ) is the same.

    The POSIX backend can be explicitly selected using the -feature-ipc_posix option to the Qt configure script. If it is enabled, the QT_POSIX_IPC macro will be defined.

  • Sandboxed applications on Apple platforms (including apps shipped through the Apple App Store): This environment requires the use of POSIX shared memory (instead of System V shared memory).

    Qt for iOS is built with support for POSIX shared memory out of the box. However, Qt for macOS builds (including those from the Qt installer) default to System V, making them unsuitable for App Store submission if QSharedMemory is needed. See above for instructions to explicitly select the POSIX backend when building Qt.

    In addition, in a sandboxed environment, the following caveats apply:

    • The key must be in the form <application group identifier>/<custom identifier>, as documented here and here .

    • The key length is limited to 30 characters.

    • On process exit, the named shared memory entries are not cleaned up, so restarting the application and re-creating the shared memory under the same name will fail. To work around this, fall back to attaching to the existing shared memory entry:

      QSharedMemory shm("DEVTEAMID.app-group/shared");
      if (!shm.create(42) && shm.error() == QSharedMemory::AlreadyExists)
          shm.attach();
      
  • Android: QSharedMemory is not supported.

Remember to lock the shared memory with lock() before reading from or writing to the shared memory, and remember to release the lock with unlock() after you are done.

QSharedMemory automatically destroys the shared memory segment when the last instance of QSharedMemory is detached from the segment, and no references to the segment remain.

Warning

QSharedMemory changes the key in a Qt-specific way, unless otherwise specified. Interoperation with non-Qt applications is achieved by first creating a default shared memory with QSharedMemory() and then setting a native key with setNativeKey() , after ensuring they use the same low-level API (System V or POSIX). When using native keys, shared memory is not protected against multiple accesses on it (for example, unable to lock() ) and a user-defined mechanism should be used to achieve such protection.

Alternative: Memory-Mapped File#

Another way to share memory between processes is by opening the same file using QFile and mapping it into memory using map() (without specifying the MapPrivateOption option). Any writes to the mapped segment will be observed by all other processes that have mapped the same file. This solution has the major advantages of being independent of the backend API and of being simpler to interoperate with from non-Qt applications. And since QTemporaryFile is a QFile , applications can use that class to achieve clean-up semantics and to create unique shared memory segments too.

To achieve locking of the shared memory segment, applications will need to deploy their own mechanisms. This can be achieved by using QBasicAtomicInteger or std::atomic in a pre-determined offset in the segment itself. Higher-level locking primitives may be available on some operating systems; for example, on Linux, pthread_mutex_create() can be passed a flag to indicate that the mutex resides in a shared memory segment.

A major drawback of using file-backed shared memory is that the operating system will attempt to write the data to permanent storage, possibly causing noticeable performance penalties. To avoid this, applications should locate a RAM-backed filesystem, such as tmpfs on Linux (see fileSystemType() ), or pass a flag to the native file-opening function to inform the OS to avoid committing the contents to storage.

File-backed shared memory must be used with care if another process participating is untrusted. The files may be truncated/shrunk and cause applications accessing memory beyond the file’s size to crash.

Linux hints on memory-mapped files#

On modern Linux systems, while the /tmp directory is often a tmpfs mount point, that is not a requirement. However, the /dev/shm directory is required to be a tmpfs and exists for this very purpose. Do note that it is world-readable and writable (like /tmp and /var/tmp), so one must be careful of the contents revealed there. Another alternative is to use the XDG Runtime Directory (see writableLocation() and RuntimeLocation ), which on Linux systems using systemd is a user-specific tmpfs.

An even more secure solution is to create a “memfd” using memfd_create(2) and use interprocess communication to pass the file descriptor, like QDBusUnixFileDescriptor or by letting the child process of a QProcess inherit it. “memfds” can also be sealed against being shrunk, so they are safe to be used when communicating with processes with a different privilege level.

FreeBSD hints on memory-mapped files#

FreeBSD also has memfd_create(2) and can pass file descriptors to other processes using the same techniques as Linux. It does not have temporary filesystems mounted by default.

Windows hints on memory-mapped files#

On Windows, the application can request the operating system avoid committing the file’s contents to permanent storage. This request is performed by passing the FILE_ATTRIBUTE_TEMPORARY flag in the dwFlagsAndAttributes CreateFile Win32 function, the _O_SHORT_LIVED flag to _open() low-level function, or by including the modifier “T” to the fopen() C runtime function.

There’s also a flag to inform the operating system to delete the file when the last handle to it is closed (FILE_FLAG_DELETE_ON_CLOSE, _O_TEMPORARY, and the “D” modifier), but do note that all processes attempting to open the file must agree on using this flag or not using it. A mismatch will likely cause a sharing violation and failure to open the file.

class PySide6.QtCore.QSharedMemory([parent=None])#

PySide6.QtCore.QSharedMemory(key[, parent=None])

Parameters:

This function overloads QSharedMemory() .

Constructs a shared memory object with the given parent. The shared memory object’s key is not set by the constructor, so the shared memory object does not have an underlying shared memory segment attached. The key must be set with setKey() or setNativeKey() before create() or attach() can be used.

See also

setKey()

Constructs a shared memory object with the given parent and with its key set to key. Because its key is set, its create() and attach() functions can be called.

PySide6.QtCore.QSharedMemory.AccessMode#

Constant

Description

QSharedMemory.ReadOnly

The shared memory segment is read-only. Writing to the shared memory segment is not allowed. An attempt to write to a shared memory segment created with ReadOnly causes the program to abort.

QSharedMemory.ReadWrite

Reading and writing the shared memory segment are both allowed.

PySide6.QtCore.QSharedMemory.SharedMemoryError#

Constant

Description

QSharedMemory.NoError

No error occurred.

QSharedMemory.PermissionDenied

The operation failed because the caller didn’t have the required permissions.

QSharedMemory.InvalidSize

A create operation failed because the requested size was invalid.

QSharedMemory.KeyError

The operation failed because of an invalid key.

QSharedMemory.AlreadyExists

A create() operation failed because a shared memory segment with the specified key already existed.

QSharedMemory.NotFound

An attach() failed because a shared memory segment with the specified key could not be found.

QSharedMemory.LockError

The attempt to lock() the shared memory segment failed because create() or attach() failed and returned false, or because a system error occurred in acquire() .

QSharedMemory.OutOfResources

A create() operation failed because there was not enough memory available to fill the request.

QSharedMemory.UnknownError

Something else happened and it was bad.

PySide6.QtCore.QSharedMemory.attach([mode=QSharedMemory.AccessMode.ReadWrite])#
Parameters:

modeAccessMode

Return type:

bool

Attempts to attach the process to the shared memory segment identified by the key that was passed to the constructor or to a call to setKey() or setNativeKey() . The access mode is ReadWrite by default. It can also be ReadOnly . Returns true if the attach operation is successful. If false is returned, call error() to determine which error occurred. After attaching the shared memory segment, a pointer to the shared memory can be obtained by calling data() .

PySide6.QtCore.QSharedMemory.constData()#
Return type:

void

Returns a const pointer to the contents of the shared memory segment, if one is attached. Otherwise it returns null. Remember to lock the shared memory with lock() before reading from or writing to the shared memory, and remember to release the lock with unlock() after you are done.

See also

attach() create()

PySide6.QtCore.QSharedMemory.create(size[, mode=QSharedMemory.AccessMode.ReadWrite])#
Parameters:
Return type:

bool

Creates a shared memory segment of size bytes with the key passed to the constructor, set with setKey() or set with setNativeKey() , then attaches to the new shared memory segment with the given access mode and returns true. If a shared memory segment identified by the key already exists, the attach operation is not performed and false is returned. When the return value is false, call error() to determine which error occurred.

See also

error()

PySide6.QtCore.QSharedMemory.detach()#
Return type:

bool

Detaches the process from the shared memory segment. If this was the last process attached to the shared memory segment, then the shared memory segment is released by the system, i.e., the contents are destroyed. The function returns true if it detaches the shared memory segment. If it returns false, it usually means the segment either isn’t attached, or it is locked by another process.

PySide6.QtCore.QSharedMemory.error()#
Return type:

SharedMemoryError

Returns a value indicating whether an error occurred, and, if so, which error it was.

See also

errorString()

PySide6.QtCore.QSharedMemory.errorString()#
Return type:

str

Returns a text description of the last error that occurred. If error() returns an error value , call this function to get a text string that describes the error.

See also

error()

PySide6.QtCore.QSharedMemory.isAttached()#
Return type:

bool

Returns true if this process is attached to the shared memory segment.

See also

attach() detach()

PySide6.QtCore.QSharedMemory.key()#
Return type:

str

Returns the key assigned with setKey() to this shared memory, or a null key if no key has been assigned, or if the segment is using a nativeKey() . The key is the identifier used by Qt applications to identify the shared memory segment.

You can find the native, platform specific, key used by the operating system by calling nativeKey() .

PySide6.QtCore.QSharedMemory.lock()#
Return type:

bool

This is a semaphore that locks the shared memory segment for access by this process and returns true. If another process has locked the segment, this function blocks until the lock is released. Then it acquires the lock and returns true. If this function returns false, it means that you have ignored a false return from create() or attach() , that you have set the key with setNativeKey() or that acquire() failed due to an unknown system error.

See also

unlock() data() acquire()

PySide6.QtCore.QSharedMemory.nativeKey()#
Return type:

str

Returns the native, platform specific, key for this shared memory object. The native key is the identifier used by the operating system to identify the shared memory segment.

You can use the native key to access shared memory segments that have not been created by Qt, or to grant shared memory access to non-Qt applications.

PySide6.QtCore.QSharedMemory.setKey(key)#
Parameters:

key – str

Sets the platform independent key for this shared memory object. If key is the same as the current key, the function returns without doing anything.

You can call key() to retrieve the platform independent key. Internally, QSharedMemory converts this key into a platform specific key. If you instead call nativeKey() , you will get the platform specific, converted key.

If the shared memory object is attached to an underlying shared memory segment, it will detach from it before setting the new key. This function does not do an attach() .

PySide6.QtCore.QSharedMemory.setNativeKey(key)#
Parameters:

key – str

Sets the native, platform specific, key for this shared memory object. If key is the same as the current native key, the function returns without doing anything. If all you want is to assign a key to a segment, you should call setKey() instead.

You can call nativeKey() to retrieve the native key. If a native key has been assigned, calling key() will return a null string.

If the shared memory object is attached to an underlying shared memory segment, it will detach from it before setting the new key. This function does not do an attach() .

The application will not be portable if you set a native key.

PySide6.QtCore.QSharedMemory.size()#
Return type:

qsizetype

Returns the size of the attached shared memory segment. If no shared memory segment is attached, 0 is returned.

Note

The size of the segment may be larger than the requested size that was passed to create() .

See also

create() attach()

PySide6.QtCore.QSharedMemory.unlock()#
Return type:

bool

Releases the lock on the shared memory segment and returns true, if the lock is currently held by this process. If the segment is not locked, or if the lock is held by another process, nothing happens and false is returned.

See also

lock()