forked from boostorg/interprocess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interprocess.qbk
7398 lines (5346 loc) · 308 KB
/
interprocess.qbk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[/
/ Copyright (c) 2005-2012 Ion Gaztanaga
/
/ Distributed under the Boost Software License, Version 1.0. (See accompanying
/ file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/]
[library Boost.Interprocess
[quickbook 1.5]
[authors [Gaztanaga, Ion]]
[copyright 2005-2015 Ion Gaztanaga]
[id interprocess]
[dirname interprocess]
[purpose Interprocess communication utilities]
[license
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
[@http://www.boost.org/LICENSE_1_0.txt])
]
]
[section:intro Introduction]
[*Boost.Interprocess] simplifies the use of common interprocess communication
and synchronization mechanisms and offers a wide range of them:
* Shared memory.
* Memory-mapped files.
* Semaphores, mutexes, condition variables and upgradable mutex types to place
them in shared memory and memory mapped files.
* Named versions of those synchronization objects, similar to UNIX/Windows
sem_open/CreateSemaphore API.
* File locking.
* Relative pointers.
* Message queues.
[*Boost.Interprocess] also offers higher-level interprocess mechanisms to allocate
dynamically portions of a shared memory or a memory mapped file (in general,
to allocate portions of a fixed size memory segment). Using these mechanisms,
[*Boost.Interprocess] offers useful tools to construct C++ objects, including
STL-like containers, in shared memory and memory mapped files:
* Dynamic creation of anonymous and named objects in a shared memory or memory
mapped file.
* STL-like containers compatible with shared memory/memory-mapped files.
* STL-like allocators ready for shared memory/memory-mapped files implementing
several memory allocation patterns (like pooling).
[section:introduction_building_interprocess Building Boost.Interprocess]
There is no need to compile [*Boost.Interprocess], since it's
a header only library. Just include your Boost header directory in your
compiler include path.
[*Boost.Interprocess] depends on
[@http://www.boost.org/libs/date_time/ [*Boost.DateTime]], which needs
separate compilation. However, the subset used by [*Boost.Interprocess] does
not need any separate compilation so the user can define `BOOST_DATE_TIME_NO_LIB`
to avoid Boost from trying to automatically link the [*Boost.DateTime].
In POSIX systems, [*Boost.Interprocess] uses pthread system calls to implement
classes like mutexes, condition variables, etc... In some operating systems,
these POSIX calls are implemented in separate libraries that are not automatically
linked by the compiler. For example, in some Linux systems POSIX pthread functions
are implemented in `librt.a` library, so you might need to add that library
when linking an executable or shared library that uses [*Boost.Interprocess].
If you obtain linking errors related to those pthread functions, please revise
your system's documentation to know which library implements them.
[endsect]
[section:tested_compilers Tested compilers]
[*Boost.Interprocess] has been tested in the following compilers/platforms:
* Visual >= 7.1
* GCC >= 4.1
* Intel 11
[endsect]
[endsect]
[section:quick_guide Quick Guide for the Impatient]
[section:qg_memory_pool Using shared memory as a pool of unnamed memory blocks]
You can just allocate a portion of a shared memory segment, copy the
message to that buffer, send the offset of that portion of shared
memory to another process, and you are done. Let's see the example:
[import ../example/doc_ipc_message.cpp]
[doc_ipc_message]
[endsect]
[section:qg_named_interprocess Creating named shared memory objects]
You want to create objects in a shared memory segment, giving a string name to them so that
any other process can find, use and delete them from the segment when the objects are not
needed anymore. Example:
[import ../example/doc_named_alloc.cpp]
[doc_named_alloc]
[endsect]
[section:qg_offset_ptr Using an offset smart pointer for shared memory]
[*Boost.Interprocess] offers offset_ptr smart pointer family
as an offset pointer that stores the distance between the address of
the offset pointer itself and the address of the pointed object.
When offset_ptr is placed in a shared memory segment, it
can point safely objects stored in the same shared
memory segment, even if the segment is mapped in
different base addresses in different processes.
This allows placing objects with pointer members
in shared memory. For example, if we want to create
a linked list in shared memory:
[import ../example/doc_offset_ptr.cpp]
[doc_offset_ptr]
To help with basic data structures, [*Boost.Interprocess] offers containers like vector,
list, map, so you can avoid these manual data structures just like with standard containers.
[endsect]
[section:qg_interprocess_container Creating vectors in shared memory]
[*Boost.Interprocess] allows creating complex objects in shared memory and memory
mapped files. For example, we can construct STL-like containers in shared memory.
To do this, we just need to create a special (managed) shared memory segment,
declare a [*Boost.Interprocess] allocator and construct the vector in shared memory
just if it was any other object.
The class that allows this complex structures in shared memory is called
[classref boost::interprocess::managed_shared_memory] and it's easy to use.
Just execute this example without arguments:
[import ../example/doc_spawn_vector.cpp]
[doc_spawn_vector]
The parent process will create an special shared memory class that allows easy construction
of many complex data structures associated with a name. The parent process executes the same
program with an additional argument so the child process opens the shared memory and uses
the vector and erases it.
[endsect]
[section:qg_interprocess_map Creating maps in shared memory]
Just like a vector, [*Boost.Interprocess] allows creating maps in
shared memory and memory mapped files. The only difference is that
like standard associative containers, [*Boost.Interprocess]'s map needs
also the comparison functor when an allocator is passed in the constructor:
[import ../example/doc_map.cpp]
[doc_map]
For a more advanced example including containers of containers, see the section
[link interprocess.allocators_containers.containers_explained.containers_of_containers Containers of containers].
[endsect]
[endsect]
[section:some_basic_explanations Some basic explanations]
[section:processes_and_threads Processes And Threads]
[*Boost.Interprocess] does not work only with processes but also with threads.
[*Boost.Interprocess] synchronization mechanisms can synchronize threads
from different processes, but also threads from the same process.
[endsect]
[section:sharing_information Sharing information between processes]
In the traditional programming model an operating system has multiple processes
running and each process has its own address space. To share information between
processes we have several alternatives:
* Two processes share information using a [*file]. To access to the data, each
process uses the usual file read/write mechanisms. When updating/reading
a file shared between processes, we need some sort of synchronization, to
protect readers from writers.
* Two processes share information that resides in the [*kernel] of the operating
system. This is the case, for example, of traditional message queues. The
synchronization is guaranteed by the operating system kernel.
* Two processes can share a [*memory] region. This is the case of classical
shared memory or memory mapped files. Once the processes set up the
memory region, the processes can read/write the data like any
other memory segment without calling the operating system's kernel. This
also requires some kind of manual synchronization between processes.
[endsect]
[section:persistence Persistence Of Interprocess Mechanisms]
One of the biggest issues with interprocess communication mechanisms is the lifetime
of the interprocess communication mechanism.
It's important to know when an interprocess communication mechanism disappears from the
system. In [*Boost.Interprocess], we can have 3 types of persistence:
* [*Process-persistence]: The mechanism lasts until all the processes that have
opened the mechanism close it, exit or crash.
* [*Kernel-persistence]: The mechanism exists until the kernel of the operating
system reboots or the mechanism is explicitly deleted.
* [*Filesystem-persistence]: The mechanism exists until the mechanism is explicitly
deleted.
Some native POSIX and Windows IPC mechanisms have different persistence so it's
difficult to achieve portability between Windows and POSIX native mechanisms.
[*Boost.Interprocess] classes have the following persistence:
[table Boost.Interprocess Persistence Table
[[Mechanism] [Persistence]]
[[Shared memory] [Kernel or Filesystem]]
[[Memory mapped file] [Filesystem]]
[[Process-shared mutex types] [Process]]
[[Process-shared semaphore] [Process]]
[[Process-shared condition] [Process]]
[[File lock] [Process]]
[[Message queue] [Kernel or Filesystem]]
[[Named mutex] [Kernel or Filesystem]]
[[Named semaphore] [Kernel or Filesystem]]
[[Named condition] [Kernel or Filesystem]]
]
As you can see, [*Boost.Interprocess] defines some mechanisms with "Kernel or Filesystem"
persistence. This is because POSIX allows this possibility to native interprocess
communication implementations. One could, for example, implement
shared memory using memory mapped files and obtain filesystem persistence (for example,
there is no proper known way to emulate kernel persistence with a user library
for Windows shared memory using native shared memory,
or process persistence for POSIX shared memory, so the only portable way is to
define "Kernel or Filesystem" persistence).
[endsect]
[section:names Names Of Interprocess Mechanisms]
Some interprocess mechanisms are anonymous objects created in shared memory or
memory-mapped files but other interprocess mechanisms need a name or identifier
so that two unrelated processes can use the same interprocess mechanism object.
Examples of this are shared memory, named mutexes and named semaphores (for example,
native windows CreateMutex/CreateSemaphore API family).
The name used to identify an interprocess mechanism is not portable, even between
UNIX systems. For this reason, [*Boost.Interprocess] limits this name to a C++ variable
identifier or keyword:
*Starts with a letter, lowercase or uppercase, such as a letter from a to z or from
A to Z. Examples: ['Sharedmemory, sharedmemory, sHaReDmEmOrY...]
*Can include letters, underscore, or digits. Examples: ['shm1, shm2and3, ShM3plus4...]
[endsect]
[section:constructors_destructors_and_resource_lifetime
Constructors, destructors and lifetime of Interprocess named resources]
Named [*Boost.Interprocess] resources (shared memory, memory mapped files,
named mutexes/conditions/semaphores) have kernel or filesystem persistency.
This means that even if all processes that have opened those resources
end, the resource will still be accessible to be opened again and the resource
can only be destructed via an explicit call to their static member `remove` function.
This behavior can be easily understood, since it's the same mechanism used
by functions controlling file opening/creation/erasure:
[table Boost.Interprocess-Filesystem Analogy
[[Named Interprocess resource] [Corresponding std file] [Corresponding POSIX operation]]
[[Constructor] [std::fstream constructor][open]]
[[Destructor] [std::fstream destructor] [close]]
[[Member `remove`] [None. `std::remove`] [unlink]]
]
Now the correspondence between POSIX and Boost.Interprocess
regarding shared memory and named semaphores:
[table Boost.Interprocess-POSIX shared memory
[[`shared_memory_object` operation] [POSIX operation]]
[[Constructor] [shm_open]]
[[Destructor] [close]]
[[Member `remove`] [shm_unlink]]
]
[table Boost.Interprocess-POSIX named semaphore
[[`named_semaphore` operation] [POSIX operation]]
[[Constructor] [sem_open]]
[[Destructor] [close]]
[[Member `remove`] [sem_unlink]]
]
The most important property is that [*destructors of named resources
don't remove the resource from the system], they only liberate resources
allocated by the system for use by the process for the named resource.
[*To remove the resource from the system the programmer must use
`remove`].
[endsect]
[section:permissions Permissions]
Named resources offered by [*Boost.Interprocess] must cope with platform-dependant
permission issues also present when creating files. If a programmer wants to
shared shared memory, memory mapped files or named synchronization mechanisms
(mutexes, semaphores, etc...) between users, it's necessary to specify
those permissions. Sadly, traditional UNIX and Windows permissions are very
different and [*Boost.Interprocess] does not try to standardize permissions,
but does not ignore them.
All named resource creation functions take an optional
[classref boost::interprocess::permissions permissions object] that can be
configured with platform-dependant permissions.
Since each mechanism can be emulated through diferent mechanisms
(a semaphore might be implement using mapped files or native semaphores)
permissions types could vary when the implementation of a named resource
changes (eg.: in Windows mutexes require `synchronize permissions`, but
that's not the case of files).
To avoid this, [*Boost.Interprocess] relies on file-like permissions,
requiring file read-write-delete permissions to open named synchronization mechanisms
(mutex, semaphores, etc.) and appropiate read or read-write-delete permissions for
shared memory. This approach has two advantages: it's similar to the UNIX philosophy
and the programmer does not need to know how the named resource is implemented.
[endsect]
[endsect]
[section:sharedmemorybetweenprocesses Sharing memory between processes]
[section:sharedmemory Shared memory]
[section:shared_memory_what_is What is shared memory?]
Shared memory is the fastest interprocess communication mechanism.
The operating system maps a memory segment in the address space of several
processes, so that several processes can read and write in that memory segment
without calling operating system functions. However, we need some kind of
synchronization between processes that read and write shared memory.
Consider what happens when a server process wants to send an HTML file to a client process
that resides in the same machine using network mechanisms:
* The server must read the file to memory and pass it to the network functions, that
copy that memory to the OS's internal memory.
* The client uses the network functions to copy the data from the OS's internal memory
to its own memory.
As we can see, there are two copies, one from memory to the network and another one
from the network to memory. And those copies are made using operating system calls
that normally are expensive. Shared memory avoids this overhead, but we need to
synchronize both processes:
* The server maps a shared memory in its address space and also gets access to a
synchronization mechanism. The server obtains exclusive access to the memory using
the synchronization mechanism and copies the file to memory.
* The client maps the shared memory in its address space. Waits until the server releases
the exclusive access and uses the data.
Using shared memory, we can avoid two data copies, but we have to synchronize the access
to the shared memory segment.
[endsect]
[section:shared_memory_steps Creating memory segments that can be shared between processes]
To use shared memory, we have to perform 2 basic steps:
* Request to the operating system a memory segment that can be shared between
processes. The user can create/destroy/open this memory using a [*shared memory object]:
['An object that represents memory that can be mapped concurrently into the
address space of more than one process.].
* Associate a part of that memory or the whole memory with the address space of the
calling process. The operating system looks for a big enough memory address range
in the calling process' address space and marks that address range as an
special range. Changes in that address range are automatically seen
by other process that also have mapped the same shared memory object.
Once the two steps have been successfully completed, the process can start writing to
and reading from the address space to send to and receive data from other processes.
Now, let's see how can we do this using [*Boost.Interprocess]:
[endsect]
[section:shared_memory_header Header]
To manage shared memory, you just need to include the following header:
[c++]
#include <boost/interprocess/shared_memory_object.hpp>
[endsect]
[section:shared_memory_creating_shared_memory_segments Creating shared memory segments]
As we've mentioned we have to use the `shared_memory_object` class to create, open
and destroy shared memory segments that can be mapped by several processes. We can
specify the access mode of that shared memory object (read only or read-write),
just as if it was a file:
* Create a shared memory segment. Throws if already created:
[c++]
using boost::interprocess;
shared_memory_object shm_obj
(create_only //only create
,"shared_memory" //name
,read_write //read-write mode
);
* To open or create a shared memory segment:
[c++]
using boost::interprocess;
shared_memory_object shm_obj
(open_or_create //open or create
,"shared_memory" //name
,read_only //read-only mode
);
* To only open a shared memory segment. Throws if does not exist:
[c++]
using boost::interprocess;
shared_memory_object shm_obj
(open_only //only open
,"shared_memory" //name
,read_write //read-write mode
);
When a shared memory object is created, its size is 0.
To set the size of the shared memory, the user must use the `truncate` function
call, in a shared memory that has been opened with read-write attributes:
[c++]
shm_obj.truncate(10000);
As shared memory has kernel or filesystem persistence, the user must explicitly
destroy it. The `remove` operation might fail returning
false if the shared memory does not exist, the file is open or the file is
still memory mapped by other processes:
[c++]
using boost::interprocess;
shared_memory_object::remove("shared_memory");
For more details regarding `shared_memory_object` see the
[classref boost::interprocess::shared_memory_object] class reference.
[endsect]
[section:shared_memory_mapping_shared_memory_segments Mapping Shared Memory Segments]
Once created or opened, a process just has to map the shared memory object in the process'
address space. The user can map the whole shared memory or just part of it. The
mapping process is done using the `mapped_region` class. The class represents
a memory region that has been mapped from a shared memory or from other devices
that have also mapping capabilities (for example, files). A `mapped_region` can be
created from any `memory_mappable` object and as you might imagine, `shared_memory_object`
is a `memory_mappable` object:
[c++]
using boost::interprocess;
std::size_t ShmSize = ...
//Map the second half of the memory
mapped_region region
( shm //Memory-mappable object
, read_write //Access mode
, ShmSize/2 //Offset from the beginning of shm
, ShmSize-ShmSize/2 //Length of the region
);
//Get the address of the region
region.get_address();
//Get the size of the region
region.get_size();
The user can specify the offset from the mappable object where the mapped region
should start and the size of the mapped region. If no offset or size is specified,
the whole mappable object (in this case, shared memory) is mapped. If the offset
is specified, but not the size, the mapped region covers from the offset until
the end of the mappable object.
For more details regarding `mapped_region` see the
[classref boost::interprocess::mapped_region] class reference.
[endsect]
[section:shared_memory_a_simple_example A Simple Example]
Let's see a simple example of shared memory use. A server process creates a
shared memory object, maps it and initializes all the bytes to a value. After that,
a client process opens the shared memory, maps it, and checks
that the data is correctly initialized:
[import ../example/doc_shared_memory.cpp]
[doc_shared_memory]
[endsect]
[section:emulation Emulation for systems without shared memory objects]
[*Boost.Interprocess] provides portable shared memory in terms of POSIX
semantics. Some operating systems don't support shared memory as defined by
POSIX:
* Windows operating systems provide shared memory using memory backed by the
paging file but the lifetime semantics are different from the ones
defined by POSIX (see [link interprocess.sharedmemorybetweenprocesses.sharedmemory.windows_shared_memory
Native windows shared memory] section for more information).
* Some UNIX systems don't fully support POSIX shared memory objects at all.
In those platforms, shared memory is emulated with mapped files created
in a "boost_interprocess" folder created in a temporary files directory.
In Windows platforms, if "Common AppData" key is present
in the registry, "boost_interprocess" folder is created in that directory
(in XP usually "C:\Documents and Settings\All Users\Application Data" and
in Vista "C:\ProgramData").
For Windows platforms without that registry key and Unix systems, shared memory is
created in the system temporary files directory ("/tmp" or similar).
Because of this emulation, shared memory has filesystem lifetime in some
of those systems.
[endsect]
[section:removing Removing shared memory]
[classref boost::interprocess::shared_memory_object shared_memory_object]
provides a static `remove` function to remove a shared memory objects.
This function [*can] fail if the shared memory objects does not exist or
it's opened by another process. Note that this function is similar to the
standard C `int remove(const char *path)` function. In UNIX systems,
`shared_memory_object::remove` calls `shm_unlink`:
* The function will remove the name of the shared memory object
named by the string pointed to by name.
* If one or more references to the shared memory object exist when
is unlinked, the name will be removed before the function returns, but the
removal of the memory object contents will be postponed until all open and
map references to the shared memory object have been removed.
* Even if the object continues to exist after the last function call, reuse of
the name will subsequently cause the creation of a
[classref boost::interprocess::shared_memory_object] instance to behave as if no
shared memory object of this name exists (that is, trying to open an object
with that name will fail and an object of the same name can be created again).
In Windows operating systems, current version supports an usually acceptable emulation
of the UNIX unlink behaviour: the file is renamed with a random name and marked as ['to
be deleted when the last open handle is closed].
[endsect]
[section:anonymous_shared_memory Anonymous shared memory for UNIX systems]
Creating a shared memory segment and mapping it can be a bit tedious when several
processes are involved. When processes are related via `fork()` operating system
call in UNIX systems a simpler method is available using anonymous shared memory.
This feature has been implemented in UNIX systems mapping the device `\dev\zero` or
just using the `MAP_ANONYMOUS` in a POSIX conformant `mmap` system call.
This feature is wrapped in [*Boost.Interprocess] using the `anonymous_shared_memory()`
function, which returns a `mapped_region` object holding an anonymous shared memory
segment that can be shared by related processes.
Here is an example:
[import ../example/doc_anonymous_shared_memory.cpp]
[doc_anonymous_shared_memory]
Once the segment is created, a `fork()` call can
be used so that `region` is used to communicate two related processes.
[endsect]
[section:windows_shared_memory Native windows shared memory]
Windows operating system also offers shared memory, but the lifetime of this
shared memory is very different to kernel or filesystem lifetime. The shared memory
is created backed by the pagefile and it's automatically destroyed when the last
process attached to the shared memory is destroyed.
Because of this reason, there is no effective way to simulate kernel or filesystem
persistence using native windows shared memory and [*Boost.Interprocess] emulates
shared memory using memory mapped files. This assures portability between POSIX
and Windows operating systems.
However, accessing native windows shared memory is a common request of
[*Boost.Interprocess] users because they want to access
to shared memory created with other process that don't use
[*Boost.Interprocess]. In order to manage the native windows shared memory
[*Boost.Interprocess] offers the
[classref boost::interprocess::windows_shared_memory windows_shared_memory] class.
Windows shared memory creation is a bit different from portable shared memory
creation: the size of the segment must be specified when creating the object and
can't be specified through `truncate` like with the shared memory object.
Take in care that when the last process attached to a shared memory is destroyed
[*the shared memory is destroyed] so there is [*no persistency] with native windows
shared memory.
Sharing memory between services and user applications is also different. To share memory
between services and user applications the name of the shared memory must start with the
global namespace prefix `"Global\\"`. This global namespace enables processes on multiple
client sessions to communicate with a service application. The server component can create
the shared memory in the global namespace. Then a client session can use the "Global\" prefix
to open that memory.
The creation of a shared memory object in the global namespace from a session other than
session zero is a privileged operation.
Let's repeat the same example presented for the portable shared memory object:
A server process creates a
shared memory object, maps it and initializes all the bytes to a value. After that,
a client process opens the shared memory, maps it, and checks
that the data is correctly initialized. Take in care that [*if the server exits before
the client connects to the shared memory the client connection will fail], because
the shared memory segment is destroyed when no proces is attached to the memory.
This is the server process:
[import ../example/doc_windows_shared_memory.cpp]
[doc_windows_shared_memory]
As we can see, native windows shared memory needs synchronization to make sure
that the shared memory won't be destroyed before the client is launched.
[endsect]
[section:xsi_shared_memory XSI shared memory]
In many UNIX systems, the OS offers another shared memory memory mechanism, XSI
(X/Open System Interfaces) shared memory segments, also known as "System V" shared memory.
This shared memory mechanism is quite popular and portable, and it's not based in file-mapping
semantics, but it uses special functions (`shmget`, `shmat`, `shmdt`, `shmctl`...).
Unlike POSIX shared memory segments, XSI shared memory segments are not identified by names but
by 'keys' usually created with `ftok`. XSI shared memory segments have kernel lifetime and
must be explicitly removed. XSI shared memory does not support copy-on-write and partial shared memory mapping
but it supports anonymous shared memory.
[*Boost.Interprocess] offers simple ([classref boost::interprocess::xsi_shared_memory xsi_shared_memory])
and managed ([classref boost::interprocess::managed_xsi_shared_memory managed_xsi_shared_memory])
shared memory classes to ease the use of XSI shared memory. It also wraps key creation with the
simple [classref boost::interprocess::xsi_key xsi_key] class.
Let's repeat the same example presented for the portable shared memory object:
A server process creates a shared memory object, maps it and initializes all the bytes to a value. After that,
a client process opens the shared memory, maps it, and checks
that the data is correctly initialized.
This is the server process:
[import ../example/doc_xsi_shared_memory.cpp]
[doc_xsi_shared_memory]
[endsect]
[endsect]
[section:mapped_file Memory Mapped Files]
[section:mapped_file_what_is What is a memory mapped file?]
File mapping is the association of a file's contents with a portion of the address space
of a process. The system creates a file mapping to associate the file and the address
space of the process. A mapped region is the portion of address space that the process
uses to access the file's contents. A single file mapping can have several mapped regions,
so that the user can associate parts of the file with the address space of the process
without mapping the entire file in the address space, since the file can be bigger
than the whole address space of the process (a 9GB DVD image file in a usual 32
bit systems). Processes read from and write to
the file using pointers, just like with dynamic memory. File mapping has the following
advantages:
* Uniform resource use. Files and memory can be treated using the same functions.
* Automatic file data synchronization and cache from the OS.
* Reuse of C++ utilities (STL containers, algorithms) in files.
* Shared memory between two or more applications.
* Allows efficient work with a large files, without mapping the whole file into memory
* If several processes use the same file mapping to create mapped regions of a file, each
process' views contain identical copies of the file on disk.
File mapping is not only used for interprocess communication, it can be used also to
simplify file usage, so the user does not need to use file-management functions to
write the file. The user just writes data to the process memory, and the operating
systems dumps the data to the file.
When two processes map the same file in memory, the memory that one process writes is
seen by another process, so memory mapped files can be used as an interprocess
communication mechanism. We can say that memory-mapped files offer the same interprocess
communication services as shared memory with the addition of filesystem persistence.
However, as the operating system has to synchronize the file contents with the memory
contents, memory-mapped files are not as fast as shared memory.
[endsect]
[section:mapped_file_steps Using mapped files]
To use memory-mapped files, we have to perform 2 basic steps:
* Create a mappable object that represent an already created file of the
filesystem. This object will be used to create multiple mapped regions of the
the file.
* Associate the whole file or parts of the file with the address space of the
calling process. The operating system looks for a big enough memory address range
in the calling process' address space and marks that address range as an
special range. Changes in that address range are automatically seen
by other process that also have mapped the same file and those changes
are also transferred to the disk automatically.
Once the two steps have been successfully completed, the process can start writing to
and reading from the address space to send to and receive data from other processes
and synchronize the file's contents with the changes made to the mapped region.
Now, let's see how can we do this using [*Boost.Interprocess]:
[endsect]
[section:mapped_file_header Header]
To manage mapped files, you just need to include the following header:
[c++]
#include <boost/interprocess/file_mapping.hpp>
[endsect]
[section:mapped_file_creating_file Creating a file mapping]
First, we have to link a file's contents with the process' address space. To do
this, we have to create a mappable object that represents that file. This is
achieved in [*Boost.Interprocess] creating a `file_mapping` object:
[c++]
using boost::interprocess;
file_mapping m_file
("/usr/home/file" //filename
,read_write //read-write mode
);
Now we can use the newly created object to create mapped regions. For more details
regarding this class see the
[classref boost::interprocess::file_mapping] class reference.
[endsect]
[section:mapped_file_mapping_regions Mapping File's Contents In Memory]
After creating a file mapping, a process just has to map the shared memory in the
process' address space. The user can map the whole shared memory or just part of it.
The mapping process is done using the `mapped_region` class. as we have said before
The class represents a memory region that has been mapped from a shared memory or from other
devices that have also mapping capabilities:
[c++]
using boost::interprocess;
std::size_t FileSize = ...
//Map the second half of the file
mapped_region region
( m_file //Memory-mappable object
, read_write //Access mode
, FileSize/2 //Offset from the beginning of shm
, FileSize-FileSize/2 //Length of the region
);
//Get the address of the region
region.get_address();
//Get the size of the region
region.get_size();
The user can specify the offset from the file where the mapped region
should start and the size of the mapped region. If no offset or size is specified,
the whole file is mapped. If the offset is specified, but not the size,
the mapped region covers from the offset until the end of the file.
If several processes map the same file, and a process modifies a memory range
from a mapped region that is also mapped by other process, the changes are
inmedially visible to other processes. However, the file contents on disk are
not updated immediately, since that would hurt performance (writing to disk
is several times slower than writing to memory). If the user wants to make sure
that file's contents have been updated, it can flush a range from the view to disk.
When the function returns, the flushing process has startd but there is not guarantee that
all data has been written to disk:
[c++]
//Flush the whole region
region.flush();
//Flush from an offset until the end of the region
region.flush(offset);
//Flush a memory range starting on an offset
region.flush(offset, size);
Remember that the offset is [*not] an offset on the file, but an offset in the
mapped region. If a region covers the second half of a file and flushes the
whole region, only the half of the file is guaranteed to have been flushed.
For more details regarding `mapped_region` see the
[classref boost::interprocess::mapped_region] class reference.
[endsect]
[section:mapped_file_a_simple_example A Simple Example]
Let's reproduce the same example described in the shared memory section, using
memory mapped files. A server process creates a shared
memory segment, maps it and initializes all the bytes to a value. After that,
a client process opens the shared memory, maps it, and checks
that the data is correctly initialized::
[import ../example/doc_file_mapping.cpp]
[doc_file_mapping]
[endsect]
[endsect]
[section:mapped_region More About Mapped Regions]
[section:mapped_region_one_class One Class To Rule Them All]
As we have seen, both `shared_memory_object` and `file_mapping` objects can be used
to create `mapped_region` objects. A mapped region created from a shared memory
object or a file mapping are the same class and this has many advantages.
One can, for example, mix in STL containers mapped regions from shared memory
and memory mapped files. Libraries that only depend on mapped regions can
be used to work with shared memory or memory mapped files without recompiling them.
[endsect]
[section:mapped_region_address_mapping Mapping Address In Several Processes]
In the example we have seen, the file or shared memory contents are mapped
to the address space of the process, but the address was chosen by the operating
system.
If several processes map the same file/shared memory, the mapping address will be
surely different in each process. Since each process might have used its address space
in a different way (allocation of more or less dynamic memory, for example), there is
no guarantee that the file/shared memory is going to be mapped in the same address.
If two processes map the same object in different addresses, this invalidates the use
of pointers in that memory, since the pointer (which is an absolute address) would
only make sense for the process that wrote it. The solution for this is to use offsets
(distance) between objects instead of pointers: If two objects are placed in the same
shared memory segment by one process, [*the address of each object will be different]
in another process but [*the distance between them (in bytes) will be the same].
So the first advice when mapping shared memory and memory mapped files is to avoid
using raw pointers, unless you know what you are doing. Use offsets between data or
relative pointers to obtain pointer functionality when an object placed in a mapped
region wants to point to an object placed in the same mapped region. [*Boost.Interprocess]
offers a smart pointer called [classref boost::interprocess::offset_ptr] that
can be safely placed in shared memory and that can be used to point to another
object placed in the same shared memory / memory mapped file.
[endsect]
[section:mapped_region_fixed_address_mapping Fixed Address Mapping]
The use of relative pointers is less efficient than using raw pointers, so if a user
can succeed mapping the same file or shared memory object in the same address in two
processes, using raw pointers can be a good idea.
To map an object in a fixed address, the user can specify that address in the
`mapped region`'s constructor:
[c++]
mapped_region region ( shm //Map shared memory
, read_write //Map it as read-write
, 0 //Map from offset 0
, 0 //Map until the end
, (void*)0x3F000000 //Map it exactly there
);
However, the user can't map the region in any address, even if the address is not
being used. The offset parameter that marks the start of the mapping region
is also limited. These limitations are explained in the next section.
[endsect]
[section:mapped_region_mapping_problems Mapping Offset And Address Limitations]
As mentioned, the user can't map the memory mappable object at any address and it can
specify the offset of the mappable object that is equivalent to the start of the mapping
region to an arbitrary value.
Most operating systems limit the mapping address and the offset of the mappable object
to a multiple of a value called [*page size]. This is due to the fact that the
[*operating system performs mapping operations over whole pages].
If fixed mapping address is used, ['offset] and ['address]
parameters should be multiples of that value.
This value is, typically, 4KB or 8KB for 32 bit operating systems.
[c++]
//These might fail because the offset is not a multiple of the page size
//and we are using fixed address mapping
mapped_region region1( shm //Map shared memory
, read_write //Map it as read-write
, 1 //Map from offset 1
, 1 //Map 1 byte
, (void*)0x3F000000 //Aligned mapping address
);
//These might fail because the address is not a multiple of the page size
mapped_region region2( shm //Map shared memory
, read_write //Map it as read-write
, 0 //Map from offset 0
, 1 //Map 1 byte
, (void*)0x3F000001 //Not aligned mapping address
);
Since the operating system performs mapping operations over whole pages, specifying
a mapping ['size] or ['offset] that are not multiple of the page size will waste
more resources than necessary. If the user specifies the following 1 byte mapping:
[c++]
//Map one byte of the shared memory object.
//A whole memory page will be used for this.
mapped_region region ( shm //Map shared memory
, read_write //Map it as read-write
, 0 //Map from offset 0
, 1 //Map 1 byte
);
The operating system will reserve a whole page that will not be reused by any
other mapping so we are going to waste [*(page size - 1)] bytes. If we want
to use efficiently operating system resources, we should create regions whose size
is a multiple of [*page size] bytes. If the user specifies the following two
mapped regions for a file with which has `2*page_size` bytes:
//Map the first quarter of the file
//This will use a whole page
mapped_region region1( shm //Map shared memory
, read_write //Map it as read-write
, 0 //Map from offset 0
, page_size/2 //Map page_size/2 bytes
);
//Map the rest of the file
//This will use a 2 pages
mapped_region region2( shm //Map shared memory
, read_write //Map it as read-write
, page_size/2 //Map from offset 0
, 3*page_size/2 //Map the rest of the shared memory
);
In this example, a half of the page is wasted in the first mapping and another
half is wasted in the second because the offset is not a multiple of the
page size. The mapping with the minimum resource usage would be to map whole pages:
//Map the whole first half: uses 1 page
mapped_region region1( shm //Map shared memory
, read_write //Map it as read-write
, 0 //Map from offset 0
, page_size //Map a full page_size
);
//Map the second half: uses 1 page
mapped_region region2( shm //Map shared memory