Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Toggle main menu visibility
Loading...
Searching...
No Matches
ipc.qdoc
Go to the documentation of this file.
1
// Copyright (C) 2022 Intel Corporation.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4
/*!
5
\page ipc.html
6
\title Inter-Process Communication
7
\ingroup groups
8
\ingroup frameworks-technologies
9
\keyword ipc
10
\ingroup explanations-networkingandconnectivity
11
12
\brief An overview of Qt's inter-process communication functionality.
13
14
Qt supports many ways of communicating with other processes running in the
15
same system or in different systems. There are basically three types of
16
inter-process communication mechanisms:
17
18
\list 1
19
\li Synchronization primitives
20
\li Exchanging of arbitrary byte-level data
21
\li Passing structured messages
22
\endlist
23
24
\section1 Synchronization primitives
25
26
Qt only provides one class for explicit inter-process synchronization:
27
\l{QSystemSemaphore}. A QSystemSemaphore is like a \l{QSemaphore} that is
28
accessible by multiple processes in the same system. It is globally
29
identified by a "key", which in Qt is represented by the \l{QNativeIpcKey}
30
class. Additionally, depending on the OS, Qt may support multiple different
31
backends for sharing memory; see the \l{Native IPC Keys} documentation for
32
more information and limitations.
33
34
It is possible to use regular thread-synchronization primitives such as
35
mutexes, wait conditions, and read-write locks, located in memory that is
36
shared between processes. Qt does not provide any class to support this,
37
but applications can use low-level operations on certain operating systems.
38
39
Other Qt classes may be used to provide higher-level locking, like
40
\l{QLockFile}, or by acquiring a unique, system-wide resource. Such
41
techniques include \l{QTcpServer}{TCP} or \l{QUdpSocket}{UDP} ports or
42
well-known names in \l{QDBusConnection::registerService}{D-Bus}.
43
44
\section1 Byte-level data sharing
45
46
Using byte-level data, applications can implement any communication
47
protocol they may choose. Sharing of byte data can be stream-oriented
48
(serialized) or can allow random access (a similar condition to
49
QFileDevice::isSequential()).
50
51
For serial communication, Qt provides a number of different classes and
52
even full modules:
53
\list
54
\li Pipes and FIFOs: \l QFile
55
\li Child processes: \l QProcess
56
\li Sockets: \l QTcpSocket, \l QUdpSocket (in \l{Qt Network})
57
\li HTTP(S): \l QNetworkAccessManager (in \l{Qt Network}) and
58
\l QHttpServer (in \l{Qt HTTP Server})
59
\li CoAP(S): \l QCoapClient (in \l{Qt CoAP})
60
\endlist
61
62
For random-access data sharing within the same system, Qt provides
63
\l{QSharedMemory}. See the \l{Shared Memory} documentation for detailed
64
information.
65
66
\section1 Structured message passing
67
68
Qt also provides a number of techniques to exchange structured messages
69
with other processes. Applications can build on top of the byte-level
70
solutions above, such as by using \l QJsonDocument or \l QXmlStreamReader /
71
\l QXmlStreamWriter over HTTP to perform JSONRPC or XMLRPC, respectively,
72
or \l QCborValue with QtCoAP.
73
74
Dedicated Qt modules for structured messages and remote procedure-calling
75
include:
76
\list
77
\li \l{Qt D-Bus}
78
\li \l{Qt Remote Objects}
79
\li \l{Qt WebSockets}
80
\endlist
81
*/
82
83
/*!
84
\page shared-memory.html
85
\title Shared Memory
86
\keyword ipc
87
\keyword shared memory
88
89
\brief Overview of the techniques for sharing memory between processes.
90
91
Qt provides two techniques to share memory with other processes in the same
92
system: \l{QSharedMemory} and memory-mapped files using \l{QFile}. Memory
93
that is shared with other processes is often referred to as a "segment",
94
and although it may have been implemented as specific segments on
95
processors with segmented memory models in the past, this is not the case
96
in any modern operating system. Shared memory segments are simply regions
97
of memory that the operating system will ensure are available to all
98
processes participating.
99
100
\note The address at which the segment is located in memory will almost
101
always be different for each process that is participating in the sharing.
102
Therefore, applications must take care to share only position-independent
103
data, such as primitive C++ types or arrays of such types.
104
105
\section1 Sharing memory using QSharedMemory
106
107
QSharedMemory provides a simple API to create a shared memory segment of a
108
given size or attach to one that was created by another process.
109
Additionally, it provides a pair of methods to \l{QSharedMemory::}{lock}
110
and \l{QSharedMemory::}{unlock} the whole segment, using an internal
111
\l{QSystemSemaphore}.
112
113
Shared memory segments and system semaphores are globally identified in the
114
system through a "key", which in Qt is represented by the \l{QNativeIpcKey}
115
class. Additionally, depending on the OS, Qt may support multiple different
116
backends for sharing memory; see the \l{Native IPC Keys} documentation for
117
more information and limitations.
118
119
QSharedMemory is designed to share memory only within the same privilege
120
level (that is, not with untrusted other processes, such as those started
121
by other users). For backends that support it, QSharedMemory will create
122
segments such that only processes with the same privilege level can attach.
123
124
\section1 Sharing memory via memory-mapped files
125
126
Most files can be mapped to memory using QFile::map() and, if the
127
\l{QFileDevice::MapPrivateOption}{MapPrivateOption} option is not specified,
128
any writes to the mapped segment will be observed by all other processes
129
that have mapped the same file. Exceptions to files that can be mapped to
130
memory include remote files found in network shares or those located in
131
certain filesystems. Even if the operating system does allow mapping remote
132
files to memory, I/O operations on the file will likely be cached and
133
delayed, thus making true memory sharing impossible.
134
135
This solution has the major advantages of being independent of any backend
136
API and of being simpler to interoperate with from non-Qt applications.
137
Since \l{QTemporaryFile} is a \l{QFile}, applications can use that class to
138
achieve clean-up semantics and to create unique shared memory segments too.
139
140
To achieve locking of the shared memory segment, applications will need to
141
deploy their own mechanisms. One way may be to use \l QLockFile. Another
142
and less costly solution is to use QAtomicInteger or \c{std::atomic} in
143
a pre-determined offset in the segment itself. Higher-level locking
144
primitives may be available on some operating systems; for example, on
145
Linux, applications can set the "pshared" flag in the mutex attribute
146
passed to \c{pthread_mutex_create()} to indicate that the mutex resides in
147
a shared memory segment.
148
149
Be aware that the operating system will likely attempt to commit to
150
permanent storage any writes made to the shared memory. This may be desired
151
or it may be a performance penalty if the file itself was meant to be
152
temporary. In that case, applications should locate a RAM-backed
153
filesystem, such as \c{tmpfs} on Linux (see
154
QStorageInfo::fileSystemType()), or pass a flag to the native file-opening
155
function to inform the OS to avoid committing the contents to storage.
156
157
It is possible to use file-backed shared memory to communicate with
158
untrusted processes, in which case the application should exercise great
159
care. See \l{shared-memory-security}{security considerations} below.
160
161
\section2 Linux hints on memory-mapped files
162
163
On modern Linux systems, while the \c{/tmp} directory is often a \c{tmpfs}
164
mount point, that is not a requirement. However, the \c{/dev/shm} directory
165
is required to be a \c{tmpfs} and exists for the very purpose of sharing
166
memory. Do note that it is world-readable and writable (like \c{/tmp} and
167
\c{/var/tmp}), so applications must be careful of the contents revealed
168
there. Another alternative is to use the XDG Runtime Directory (see
169
QStandardPaths::writableLocation() and \l{QStandardPaths::RuntimeLocation}),
170
which on Linux systems using systemd is a user-specific \c{tmpfs}.
171
172
An even more secure solution is to create a "memfd" using \c{memfd_create(2)}
173
and use interprocess communication to pass the file descriptor, like
174
\l{QDBusUnixFileDescriptor} or by letting the child process of a \l{QProcess}
175
inherit it. "memfds" can also be sealed against being shrunk, so they are
176
safe to be used when communicating with processes with a different privilege
177
level.
178
179
\section2 FreeBSD hints on memory-mapped files
180
181
FreeBSD also has \c{memfd_create(2)} and can pass file descriptors to other
182
processes using the same techniques as Linux. It does not have temporary
183
filesystems mounted by default.
184
185
\section2 Windows hints on memory-mapped files
186
187
On Windows, the application can request the operating system avoid saving
188
the file's contents on permanent storage. This request is performed by
189
passing the \c{FILE_ATTRIBUTE_TEMPORARY} flag in the
190
\c{dwFlagsAndAttributes} parameter to the \c{CreateFile} Win32 function,
191
the \c{_O_SHORT_LIVED} flag to \c{_open()} low-level function, or by
192
including the modifier "T" to the
193
\c{fopen()} C runtime function.
194
195
There's also a flag to inform the operating system to delete the file when
196
the last handle to it is closed (\c{FILE_FLAG_DELETE_ON_CLOSE},
197
\c{_O_TEMPORARY}, and the "D" modifier), but do note that all processes
198
attempting to open the file must agree on using this flag or not using it. A
199
mismatch will likely cause a sharing violation and failure to open the file.
200
201
\target shared-memory-security
202
\section1 Security considerations
203
204
QSharedMemory inherits all security considerations of
205
\l{native-ipc-keys-security}{native IPC keys}. This section covers the
206
contents of shared memory, which applies both to QSharedMemory and to
207
memory-mapped files.
208
209
Every process that has mapped a segment with write access can modify its
210
contents at any time. So handle data read from shared memory with the
211
same care as any other untrusted input:
212
\list
213
\li Before using any offset, length, count, or index read from the
214
segment, check it against the size of the segment. That size is
215
returned by \l QSharedMemory::size() or passed to \l QFile::map().
216
Never follow a pointer or offset stored in the segment without
217
such a check.
218
\li Locking is cooperative. Like any locking scheme an application
219
implements for memory-mapped files, \l QSharedMemory::lock() only
220
excludes other processes that use it. A misbehaving peer can write to
221
the segment without holding the lock. Such a process can thus change
222
data while another is reading it, even between validating a value and
223
using it. Copy the data into private memory first, then validate and
224
use the copy.
225
\li Consider placing a self-describing header in the segment to make it
226
possible to detect inconsistent or partially written contents. For
227
example, such a header could supply a format version, the length of
228
the payload and a checksum.
229
\li Mapping a segment read-only, by attaching with
230
QSharedMemory::ReadOnly or by mapping a file opened with
231
QIODevice::ReadOnly, only restricts the mapping in the calling
232
process. Other processes may still modify the segment.
233
\endlist
234
235
Just as other processes may interfere with what you read, they may also
236
read anything you write. Every process able to attach to a segment or open
237
the file can read its contents. As explained in
238
\l{Leftover objects and resource usage}, the data you write to a segment
239
may remain in memory or on storage after the application exits. Avoid
240
placing secrets in shared memory, or clear them once they are no longer
241
needed.
242
243
A process with write access may also be able to shrink the segment after
244
other processes have mapped it. Accessing the part of the mapping beyond
245
the new end of the segment raises a \c{SIGBUS} signal, which terminates
246
the process by default. This applies to memory-mapped files and to
247
QSharedMemory with the POSIX Realtime backend. For QSharedMemory, Qt
248
attempts to prevent this where the operating system supports it, but such
249
protection is not available on all platforms. For memory-mapped files,
250
a sealed "memfd" avoids the problem (see
251
\l{Linux hints on memory-mapped files}).
252
*/
253
254
/*!
255
\page native-ipc-keys.html
256
\title Native IPC Keys
257
\keyword ipc
258
\keyword shared memory
259
\keyword system semaphore
260
261
\brief An overview of keys for QSharedMemory and QSystemSemaphore.
262
263
The \l QSharedMemory and \l QSystemSemaphore classes identify their
264
resource using a system-wide identifier known as a "key". The low-level key
265
value as well as the key type are encapsulated in Qt using the \l
266
QNativeIpcKey class. That class also provides the proper means of
267
exchanging the key with other processes, by way of
268
QNativeIpcKey::toString() and QNativeIpcKey::fromString().
269
270
Qt currently supports three distinct backends for those two classes, which
271
match the values available in the \l{QNativeIpcKey::Type} enumeration.
272
\list
273
\li POSIX Realtime extensions (IEEE 1003.1b, POSIX.1b)
274
\li X/Open System Interfaces (XSI) or System V (SVr4), though also now part of POSIX
275
\li Windows primitives
276
\endlist
277
278
As the name indicates, the Windows primitives are only available on the
279
Windows operating system, where they are the default backend. The other two
280
are usually both available on Unix operating systems. The following table
281
provides an overview of typical availability since Qt 6.6:
282
283
\table
284
\header \li Operating system \li POSIX \li System V \li Windows
285
\row \li Android \li \li \li
286
\row \li INTEGRITY \li \li \li
287
\row \li QNX \li Yes \li \li
288
\row \li \macos \li Yes \li Usually (1) \li
289
\row \li Other Apple OSes \li Yes \li \li
290
\row \li Other Unix systems \li Yes \li Yes \li
291
\row \li Windows \li Rarely (2) \li \li Yes
292
\endtable
293
294
\note 1 Sandboxed \macos applications, which include all applications
295
distributed via the Apple App Store, may not use System V objects.
296
297
\note 2 Some GCC-compatible C runtimes on Windows provide POSIX-compatible
298
shared memory support, but this is rare. It is always absent with the
299
Microsoft compiler.
300
301
To determine whether a given key type is supported, applications should
302
call QSharedMemory::isKeyTypeSupported() and
303
QSystemSemaphore::isKeyTypeSupported().
304
305
QNativeIpcKey also provides support for compatibility with Qt applications
306
prior to its introduction. The following sections detail the limitations of
307
the backends, the contents of the string keys themselves, and
308
compatibility.
309
310
\section1 Cross-platform safe key format
311
312
QNativeIpcKey::setNativeKey() and QNativeIpcKey::nativeKey() handle the
313
low-level native key, which may be used with the native APIs and shared
314
with other, non-Qt processes (see below for the API). This format is not
315
usually cross-platform, so both QSharedMemory and QSystemSemaphore provide
316
a function to translate a cross-platform identifier string to the native
317
key: QSharedMemory::platformSafeKey() and
318
QSystemSemaphore::platformSafeKey().
319
320
The length of the cross-platform key on most platforms is the same as that
321
of a file name, but is severely limited on Apple platforms to only 30
322
usable bytes (be mindful of UTF-8 encoding if using characters outside the
323
US-ASCII range). The format of the key is also similar to that of a file
324
path component, meaning it should not contain any characters not allowed in
325
file names, in particular those that separate path components (slash and
326
backslash), with the exception of sandboxed applications on Apple operating
327
systems. The following are good examples of cross-platform keys: "myapp",
328
"org.example.myapp", "org.example.myapp-12345". Note that it is up to the
329
caller to prevent oversized keys, and to ensure that the key contains legal
330
characters on the respective platform. Qt will silently truncate keys that
331
are too long.
332
333
\b{Apple sandbox limitations:} if the application is running inside of a
334
sandbox in an Apple operating system, the key must be in a very specific
335
format: \c {<application group identifier>/<custom identifier>}. Sandboxing
336
is implied for all applications distributed through the Apple App Store.
337
See Apple's documentation
338
\l{https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW24}
339
{here} and \l{https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_application-groups}
340
{here} for more information, including how to obtain the application's group identifier.
341
342
\section1 Native key format
343
344
This section details the format of the native keys of the supported
345
backends.
346
347
\section3 POSIX Realtime
348
Native keys resemble file names and may contain any character that file
349
names do, except for a slash. POSIX requires the first character in the key
350
name to be a slash and leaves undetermined whether any additional slashes
351
are permitted. On most operating systems, the key length is the same as a
352
file name, but it is limited to 32 characters on Apple operating systems
353
(this includes the first slash and the terminating null, so only 30 usable
354
characters are possible).
355
356
The following are good examples of native POSIX keys: "/myapp",
357
"/org.example.myapp", "/org.example.myapp-12345".
358
359
QSharedMemory::platformSafeKey() and QSystemSemaphore::platformSafeKey()
360
simply prepend the slash. On Apple operating systems, they also truncate
361
the result to the available size.
362
363
\section3 Windows
364
Windows key types are NT
365
\l{https://learn.microsoft.com/en-us/windows/win32/sync/object-namespaces}{kernel
366
object names} and may be up to \c{MAX_PATH} (260) characters in length.
367
They look like relative paths (that is, they don't start with a backslash
368
or a drive letter), but unlike file names on Windows, they are
369
case-sensitive.
370
371
The following are good examples of native Windows keys: "myapp",
372
"org.example.myapp", "org.example.myapp-12345".
373
374
QSharedMemory::platformSafeKey() and QSystemSemaphore::platformSafeKey()
375
insert a prefix to disambiguate shared memory and system semaphores,
376
respectively.
377
378
\section3 X/Open System Interfaces (XSI) / System V
379
System V keys take the form of the name of a file in the system, and thus
380
have the exact same limitations as file paths do. Both QSharedMemory and
381
QSystemSemaphore will create this file if it does not exist when creating
382
the object. If auto-removal is disabled, it may also be shared between
383
QSharedMemory and QSystemSemaphore without conflict and can be any extant
384
file (for example, it can be the process executable itself, see
385
QCoreApplication::applicationFilePath()). The path should be an absolute
386
one to avoid mistakes due to different current directories.
387
388
QSharedMemory::platformSafeKey() and QSystemSemaphore::platformSafeKey()
389
always return an absolute path. If the input was already absolute, they
390
will return their input unchanged. Otherwise, they will prepend a suitable
391
path where the application usually has permission to create files in.
392
393
\section1 Ownership
394
395
Shared memory and system semaphore objects need to be created before use,
396
which is accomplished with QSharedMemory::create() or by passing
397
QSystemSemaphore::Create to the constructor, respectively.
398
399
On Unix systems, the Qt classes that created the object will be responsible
400
for cleaning up the object in question. Therefore, if the application with
401
that C++ object exits uncleanly (a crash, qFatal(), etc.), the object may
402
be left behind. If that happens, applications may fail to create the
403
object again and should instead attach to an existing one. For example, for
404
QSharedMemory:
405
406
\code
407
if (!shm.create(4096) && shm.error() == QSharedMemory::AlreadyExists)
408
shm.attach();
409
\endcode
410
411
Re-attaching to a QSystemSemaphore is probably unwise, as the token counter
412
in it is probably in an unknown state and therefore may lead to deadlocks.
413
414
\section3 POSIX Realtime
415
POSIX Realtime object ownership is patterned after files, in the sense that
416
they exist independent of any process using them or not. Qt is unable to
417
determine if the object is still in use, so auto-removal will remove it
418
even then, which will make attaching to the same object impossible but
419
otherwise not affecting existing attachments.
420
421
Prior to Qt 6.6, Qt never cleaned up POSIX Realtime objects, except on QNX.
422
423
\section3 X/Open System Interfaces (XSI) / System V
424
There are two resources managed by the Qt classes: the file the key refers
425
to and the object itself. QSharedMemory manages the object cooperatively:
426
the last attachment is responsible for removing the object itself and then
427
removing the key file. QSystemSemaphore will remove the object if and only
428
if it was passed QSystemSemaphore::Create; additionally, if it created the
429
key file, it will remove that too.
430
431
Since Qt 6.6, it is possible to ask either class not to clean up.
432
433
\section3 Windows
434
The operating system owns the object and will clean up after the last
435
handle to the object is closed.
436
437
\target native-ipc-keys-security
438
\section1 Security considerations
439
440
Shared memory segments and system semaphores form a boundary between
441
processes. QSharedMemory and QSystemSemaphore name, create, open, and map
442
the underlying operating system objects. However, they can not authenticate
443
the processes on the other side or validate what those processes do with
444
the objects. The application is responsible for deciding which peers it
445
trusts and for validating any data it receives from them.
446
447
\section2 Predictable keys and pre-existing objects
448
449
The native key is a deterministic function of the key passed to
450
\c{platformSafeKey()} or \c{legacyNativeKey()}, and that key is often a
451
constant compiled into the application. Any process that knows or
452
guesses it can compute the same native key, and can create the object
453
before the application does. Depending on how the application reacts,
454
this can result in:
455
\list
456
\li a denial of service, because \l QSharedMemory::create() fails with
457
QSharedMemory::AlreadyExists;
458
\li the application using an object that another process created, with
459
a size, initial contents or semaphore count chosen by that process.
460
\endlist
461
462
When the shared resource is meant for a specific peer, consider:
463
\list
464
\li Generating a unique key for each instance and passing the resulting
465
key to the peer over a trusted channel using
466
\l QNativeIpcKey::toString(). For example, \l QUuid::createUuid() or
467
\l QRandomGenerator can supply a key and you can trust the command
468
line to supply it to a child process started with \l QProcess.
469
\li Treating an unexpected QSharedMemory::AlreadyExists error as a sign
470
of possible interference rather than as a reason to attach.
471
\li Verifying the size and the header of a segment after attaching to it.
472
\endlist
473
474
On Windows, \c{platformSafeKey()} preserves a \c{Local\\} or \c{Global\\}
475
prefix in the key. Objects in the \c{Global\\} namespace are shared by all
476
sessions on the machine, including the sessions of other users. This means
477
that a process in another session may be able to create an object of that
478
name first. Only use the \c{Global\\} namespace when you need to share the
479
object across sessions.
480
481
On the System V backend, the native key is the path of a file that Qt
482
creates if needed and passes to \c{ftok()}. If other users can write
483
to the directory that file is in, those users can create or replace the file
484
first, so the problem is not limited to processes of the same user.
485
For example \c{legacyNativeKey()} uses \c{/tmp/}, which other users can
486
access. Prefer a directory that only the user can write to, such as
487
\l{QStandardPaths::RuntimeLocation}, which \c{platformSafeKey()} uses for
488
relative keys. Note also that \c{ftok()} can map different files to the
489
same System V key, so unrelated applications may collide.
490
491
\section2 Native keys from untrusted sources
492
493
QNativeIpcKey::fromString(), QSharedMemory::setNativeKey() and
494
QSystemSemaphore::setNativeKey() accept a native key as is, and Qt opens
495
or creates exactly the object it names. For the System V backend, the
496
native key is a file path that Qt may create and later delete. A native
497
key received from an untrusted source, such as the command line, a file,
498
or a network connection, can therefore direct the application to an
499
arbitrary object or file. Only accept native keys from trusted peers, or
500
verify that the key has the expected form before using it.
501
502
\section2 Leftover objects and resource usage
503
504
Shared memory segments and system semaphores are named system-wide
505
resources that can outlive the processes using them. Objects are left
506
behind when a process exits uncleanly, when automatic clean-up has been
507
disabled, or when the backend cannot determine that the last process has
508
detached. A later process may then attach to an object whose size,
509
contents or semaphore count are not what it expects. For QSystemSemaphore,
510
pass QSystemSemaphore::Create to reset a semaphore to a known initial value.
511
512
Leftover segments keep consuming memory, often RAM-backed (for example in
513
\c{/dev/shm} on Linux), until they are explicitly removed or the system is
514
restarted. Applications that create segments repeatedly, for example one
515
per request or per client, should define clearly which process is
516
responsible for removing each one, and should limit both their number and
517
their size. This is especially important if other processes control the size
518
or the creation of segments.
519
520
\section1 Interoperability with old Qt applications
521
522
The QNativeIpcKey class was introduced in Qt 6.6. Prior to this version,
523
QSharedMemory and QSystemSemaphore backends were determined at the time of
524
Qt's own build. For Windows systems, it was always the Windows backend. For
525
Unix systems, it defaulted to the System V backend if the configuration
526
script determined it was available. If it was not available, it fell back
527
to the POSIX one. The POSIX backend could be explicitly
528
selected using the \c{-feature-ipc_posix} option to the Qt configure
529
script; if it was enabled, the \c{QT_POSIX_IPC} macro would be defined.
530
531
Qt 6.6 retains the configure script option but it no longer controls the
532
availability of the backends. Instead, it changes what
533
QNativeIpcKey::legacyDefaultTypeForOs() will return. Applications that need
534
to retain compatibility must use this key type exclusively to guarantee
535
interoperability.
536
537
The API in both QSharedMemory and QSystemSemaphore had the concept of a
538
cross-platform key, which is now deprecated in favor of using
539
QSharedMemory::legacyNativeKey() and QSystemSemaphore::legacyNativeKey().
540
Those two functions produce the same native key as the deprecated functions
541
did in prior versions. If the old code was for example:
542
543
\code
544
QSharedMemory shm("org.example.myapplication");
545
QSystemSemaphore sem("org.example.myapplication");
546
\endcode
547
548
It can be updated to be:
549
\code
550
QSharedMemory shm(QSharedMemory::legacyNativeKey("org.example.myapplication"));
551
QSystemSemaphore sem(QSystemSemaphore::legacyNativeKey("org.example.myapplication"));
552
\endcode
553
554
If the two applications exchanged native keys, there is no need to update
555
code such as:
556
557
\code
558
QSharedMemory shm;
559
shm.setNativeKey(key);
560
\endcode
561
562
Though if the older application did accept a native key, the new one may
563
opt to use \c{platformSafeKey()} with a second argument of
564
QNativeIpcKey::legacyDefaultTypeForOs().
565
566
\section3 X/Open System Interfaces (XSI) / System V
567
Never use existing files for QSharedMemory keys, as the old Qt application
568
may attempt to remove it. Instead, let QSharedMemory create it.
569
570
\section1 Interoperability with non-Qt applications
571
572
Interoperability with non-Qt applications is possible, with some limitations:
573
\list
574
\li Creation of shared memory segments must not race
575
\li QSharedMemory support for locking the segment is unavailable
576
\endlist
577
578
Communication with non-Qt applications must always be through the native
579
key.
580
581
QSharedMemory always maps the entire segment to memory. The non-Qt
582
application may choose to only map a subset of it to memory, with no ill
583
effects.
584
585
\section3 POSIX Realtime
586
POSIX shared memory can be opened using
587
\l{https://pubs.opengroup.org/onlinepubs/9699919799/functions/shm_open.html}{shm_open()}
588
and POSIX system semaphores can be opened using
589
\l{https://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_open.html}{sem_open()}.
590
591
Both of those functions take a \c name parameter that is the result of
592
QNativeIpcKey::nativeKey(), encoded for file names using
593
QFile::encodeName() / QFile::decodeName().
594
595
\section3 Windows
596
Windows shared memory objects can be opened using
597
\l{https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-createfilemappingw}{CreateFileMappingW}
598
and Windows system semaphore objects can be opened using
599
\l{https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createsemaphorew}{CreateSemaphoreW}.
600
Despite the name of both functions starting with "Create", they are able
601
to attach to existing objects.
602
603
The \c lpName parameter to those functions is the result of
604
QNativeIpcKey::nativeKey(), without transformation.
605
606
If the foreign application uses the non-Unicode version of those functions
607
(ending in "A"), the name can be converted to and from 8-bit using QString.
608
609
\section3 X/Open System Interfaces (XSI) / System V
610
System V shared memory can be obtained using
611
\l{https://pubs.opengroup.org/onlinepubs/9699919799/functions/shmget.html}{shmget()}
612
and System V system semaphores can be obtained using
613
\l{https://pubs.opengroup.org/onlinepubs/9699919799/functions/semget.html}{semget()}.
614
615
The \c{key} parameter to either of those functions is the result of the
616
\l{https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftok.html}{ftok()}
617
function when passed the file name obtained from QNativeIpcKey::nativeKey()
618
with an \c id of 81 or 0x51 (the ASCII capital letter 'Q').
619
620
System V semaphore objects may contain multiple semaphores, but
621
QSystemSemaphore only uses the first one (number 0 for \c{sem_num}).
622
623
Both QSharedMemory and QSystemSemaphore default to removing the object
624
using the \c{IPC_RMID} operation to \c{shmctl()} and \c{semctl()}
625
respectively if they are the last attachment.
626
*/
qtbase
src
corelib
doc
src
ipc.qdoc
Generated on
for Qt by
1.18.0