]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man2/mmap.2
ldd.1, localedef.1, add_key.2, chroot.2, clone.2, fork.2, futex.2, get_mempolicy...
[thirdparty/man-pages.git] / man2 / mmap.2
1 .\" Copyright (C) 1996 Andries Brouwer <aeb@cwi.nl>
2 .\" and Copyright (C) 2006, 2007 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein. The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .\" Modified 1997-01-31 by Eric S. Raymond <esr@thyrsus.com>
27 .\" Modified 2000-03-25 by Jim Van Zandt <jrv@vanzandt.mv.com>
28 .\" Modified 2001-10-04 by John Levon <moz@compsoc.man.ac.uk>
29 .\" Modified 2003-02-02 by Andi Kleen <ak@muc.de>
30 .\" Modified 2003-05-21 by Michael Kerrisk <mtk.manpages@gmail.com>
31 .\" MAP_LOCKED works from 2.5.37
32 .\" Modified 2004-06-17 by Michael Kerrisk <mtk.manpages@gmail.com>
33 .\" Modified 2004-09-11 by aeb
34 .\" Modified 2004-12-08, from Eric Estievenart <eric.estievenart@free.fr>
35 .\" Modified 2004-12-08, mtk, formatting tidy-ups
36 .\" Modified 2006-12-04, mtk, various parts rewritten
37 .\" 2007-07-10, mtk, Added an example program.
38 .\" 2008-11-18, mtk, document MAP_STACK
39 .\"
40 .TH MMAP 2 2016-07-17 "Linux" "Linux Programmer's Manual"
41 .SH NAME
42 mmap, munmap \- map or unmap files or devices into memory
43 .SH SYNOPSIS
44 .nf
45 .B #include <sys/mman.h>
46 .sp
47 .BI "void *mmap(void *" addr ", size_t " length \
48 ", int " prot ", int " flags ,
49 .BI " int " fd ", off_t " offset );
50 .BI "int munmap(void *" addr ", size_t " length );
51 .fi
52
53 See NOTES for information on feature test macro requirements.
54 .SH DESCRIPTION
55 .BR mmap ()
56 creates a new mapping in the virtual address space of
57 the calling process.
58 The starting address for the new mapping is specified in
59 .IR addr .
60 The
61 .I length
62 argument specifies the length of the mapping.
63
64 If
65 .I addr
66 is NULL,
67 then the kernel chooses the address at which to create the mapping;
68 this is the most portable method of creating a new mapping.
69 If
70 .I addr
71 is not NULL,
72 then the kernel takes it as a hint about where to place the mapping;
73 on Linux, the mapping will be created at a nearby page boundary.
74 .\" Before Linux 2.6.24, the address was rounded up to the next page
75 .\" boundary; since 2.6.24, it is rounded down!
76 The address of the new mapping is returned as the result of the call.
77
78 The contents of a file mapping (as opposed to an anonymous mapping; see
79 .B MAP_ANONYMOUS
80 below), are initialized using
81 .I length
82 bytes starting at offset
83 .I offset
84 in the file (or other object) referred to by the file descriptor
85 .IR fd .
86 .I offset
87 must be a multiple of the page size as returned by
88 .IR sysconf(_SC_PAGE_SIZE) .
89 .LP
90 The
91 .I prot
92 argument describes the desired memory protection of the mapping
93 (and must not conflict with the open mode of the file).
94 It is either
95 .B PROT_NONE
96 or the bitwise OR of one or more of the following flags:
97 .TP 1.1i
98 .B PROT_EXEC
99 Pages may be executed.
100 .TP
101 .B PROT_READ
102 Pages may be read.
103 .TP
104 .B PROT_WRITE
105 Pages may be written.
106 .TP
107 .B PROT_NONE
108 Pages may not be accessed.
109 .LP
110 The
111 .I flags
112 argument determines whether updates to the mapping
113 are visible to other processes mapping the same region,
114 and whether updates are carried through to the underlying file.
115 This behavior is determined by including exactly one
116 of the following values in
117 .IR flags :
118 .TP
119 .B MAP_SHARED
120 Share this mapping.
121 Updates to the mapping are visible to other processes that map this file,
122 and are carried through to the underlying file.
123 (To precisely control when updates are carried through
124 to the underlying file requires the use of
125 .BR msync (2).)
126 .TP
127 .B MAP_PRIVATE
128 Create a private copy-on-write mapping.
129 Updates to the mapping are not visible to other processes
130 mapping the same file, and are not carried through to
131 the underlying file.
132 It is unspecified whether changes made to the file after the
133 .BR mmap ()
134 call are visible in the mapped region.
135 .LP
136 Both of these flags are described in POSIX.1-2001 and POSIX.1-2008.
137
138 In addition, zero or more of the following values can be ORed in
139 .IR flags :
140 .TP
141 .BR MAP_32BIT " (since Linux 2.4.20, 2.6)"
142 Put the mapping into the first 2 Gigabytes of the process address space.
143 This flag is supported only on x86-64, for 64-bit programs.
144 It was added to allow thread stacks to be allocated somewhere
145 in the first 2GB of memory,
146 so as to improve context-switch performance on some early
147 64-bit processors.
148 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
149 Modern x86-64 processors no longer have this performance problem,
150 so use of this flag is not required on those systems.
151 The
152 .B MAP_32BIT
153 flag is ignored when
154 .B MAP_FIXED
155 is set.
156 .TP
157 .B MAP_ANON
158 Synonym for
159 .BR MAP_ANONYMOUS .
160 Deprecated.
161 .TP
162 .B MAP_ANONYMOUS
163 The mapping is not backed by any file;
164 its contents are initialized to zero.
165 The
166 .I fd
167 and
168 .I offset
169 arguments are ignored;
170 however, some implementations require
171 .I fd
172 to be \-1 if
173 .B MAP_ANONYMOUS
174 (or
175 .BR MAP_ANON )
176 is specified,
177 and portable applications should ensure this.
178 The use of
179 .B MAP_ANONYMOUS
180 in conjunction with
181 .B MAP_SHARED
182 is supported on Linux only since kernel 2.4.
183 .TP
184 .B MAP_DENYWRITE
185 This flag is ignored.
186 .\" Introduced in 1.1.36, removed in 1.3.24.
187 (Long ago, it signaled that attempts to write to the underlying file
188 should fail with
189 .BR ETXTBUSY .
190 But this was a source of denial-of-service attacks.)
191 .TP
192 .B MAP_EXECUTABLE
193 This flag is ignored.
194 .\" Introduced in 1.1.38, removed in 1.3.24. Flag tested in proc_follow_link.
195 .\" (Long ago, it signaled that the underlying file is an executable.
196 .\" However, that information was not really used anywhere.)
197 .\" Linus talked about DOS related to MAP_EXECUTABLE, but he was thinking of
198 .\" MAP_DENYWRITE?
199 .TP
200 .B MAP_FILE
201 Compatibility flag.
202 Ignored.
203 .\" On some systems, this was required as the opposite of
204 .\" MAP_ANONYMOUS -- mtk, 1 May 2007
205 .TP
206 .B MAP_FIXED
207 Don't interpret
208 .I addr
209 as a hint: place the mapping at exactly that address.
210 .I addr
211 must be a multiple of the page size.
212 If the memory region specified by
213 .I addr
214 and
215 .I len
216 overlaps pages of any existing mapping(s), then the overlapped
217 part of the existing mapping(s) will be discarded.
218 If the specified address cannot be used,
219 .BR mmap ()
220 will fail.
221 Because requiring a fixed address for a mapping is less portable,
222 the use of this option is discouraged.
223 .TP
224 .B MAP_GROWSDOWN
225 Used for stacks.
226 Indicates to the kernel virtual memory system that the mapping
227 should extend downward in memory.
228 .TP
229 .BR MAP_HUGETLB " (since Linux 2.6.32)"
230 Allocate the mapping using "huge pages."
231 See the Linux kernel source file
232 .I Documentation/vm/hugetlbpage.txt
233 for further information, as well as NOTES, below.
234 .TP
235 .BR MAP_HUGE_2MB ", " MAP_HUGE_1GB " (since Linux 3.8)"
236 .\" See https://lwn.net/Articles/533499/
237 Used in conjunction with
238 .B MAP_HUGETLB
239 to select alternative hugetlb page sizes (respectively, 2 MB and 1 GB)
240 on systems that support multiple hugetlb page sizes.
241
242 More generally, the desired huge page size can be configured by encoding
243 the base-2 logarithm of the desired page size in the six bits at the offset
244 .BR MAP_HUGE_SHIFT .
245 (A value of zero in this bit field provides the default huge page size;
246 the default huge page size can be discovered vie the
247 .I Hugepagesize
248 field exposed by
249 .IR /proc/meminfo .)
250 Thus, the above two constants are defined as:
251
252 .nf
253 .in +4n
254 #define MAP_HUGE_2MB (21 << MAP_HUGE_SHIFT)
255 #define MAP_HUGE_1GB (30 << MAP_HUGE_SHIFT)
256 .in
257 .fi
258
259 The range of huge page sizes that are supported by the system
260 can be discovered by listing the subdirectories in
261 .IR /sys/kernel/mm/hugepages .
262 .TP
263 .BR MAP_LOCKED " (since Linux 2.5.37)"
264 Mark the mmaped region to be locked in the same way as
265 .BR mlock (2).
266 This implementation will try to populate (prefault) the whole range but
267 the mmap call doesn't fail with
268 .B ENOMEM
269 if this fails.
270 Therefore major faults might happen later on.
271 So the semantic is not as strong as
272 .BR mlock (2).
273 One should use
274 .BR mmap (2)
275 plus
276 .BR mlock (2)
277 when major faults are not acceptable after the initialization of the mapping.
278 The
279 .BR MAP_LOCKED
280 flag is ignored in older kernels.
281 .\" If set, the mapped pages will not be swapped out.
282 .TP
283 .BR MAP_NONBLOCK " (since Linux 2.5.46)"
284 Only meaningful in conjunction with
285 .BR MAP_POPULATE .
286 Don't perform read-ahead:
287 create page tables entries only for pages
288 that are already present in RAM.
289 Since Linux 2.6.23, this flag causes
290 .BR MAP_POPULATE
291 to do nothing.
292 One day, the combination of
293 .BR MAP_POPULATE
294 and
295 .BR MAP_NONBLOCK
296 may be reimplemented.
297 .TP
298 .B MAP_NORESERVE
299 Do not reserve swap space for this mapping.
300 When swap space is reserved, one has the guarantee
301 that it is possible to modify the mapping.
302 When swap space is not reserved one might get
303 .B SIGSEGV
304 upon a write
305 if no physical memory is available.
306 See also the discussion of the file
307 .I /proc/sys/vm/overcommit_memory
308 in
309 .BR proc (5).
310 In kernels before 2.6, this flag had effect only for
311 private writable mappings.
312 .TP
313 .BR MAP_POPULATE " (since Linux 2.5.46)"
314 Populate (prefault) page tables for a mapping.
315 For a file mapping, this causes read-ahead on the file.
316 This will help to reduce blocking on page faults later.
317 .BR MAP_POPULATE
318 is supported for private mappings only since Linux 2.6.23.
319 .TP
320 .BR MAP_STACK " (since Linux 2.6.27)"
321 Allocate the mapping at an address suitable for a process
322 or thread stack.
323 This flag is currently a no-op,
324 but is used in the glibc threading implementation so that
325 if some architectures require special treatment for stack allocations,
326 support can later be transparently implemented for glibc.
327 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
328 .\" commit cd98a04a59e2f94fa64d5bf1e26498d27427d5e7
329 .\" http://thread.gmane.org/gmane.linux.kernel/720412
330 .\" "pthread_create() slow for many threads; also time to revisit 64b
331 .\" context switch optimization?"
332 .TP
333 .BR MAP_UNINITIALIZED " (since Linux 2.6.33)"
334 Don't clear anonymous pages.
335 This flag is intended to improve performance on embedded devices.
336 This flag is honored only if the kernel was configured with the
337 .B CONFIG_MMAP_ALLOW_UNINITIALIZED
338 option.
339 Because of the security implications,
340 that option is normally enabled only on embedded devices
341 (i.e., devices where one has complete control of the contents of user memory).
342 .LP
343 Of the above flags, only
344 .B MAP_FIXED
345 is specified in POSIX.1-2001 and POSIX.1-2008.
346 However, most systems also support
347 .B MAP_ANONYMOUS
348 (or its synonym
349 .BR MAP_ANON ).
350 .LP
351 Some systems document the additional flags
352 .BR MAP_AUTOGROW ,
353 .BR MAP_AUTORESRV ,
354 .BR MAP_COPY ,
355 and
356 .BR MAP_LOCAL .
357 .LP
358 Memory mapped by
359 .BR mmap ()
360 is preserved across
361 .BR fork (2),
362 with the same attributes.
363 .LP
364 A file is mapped in multiples of the page size.
365 For a file that is not
366 a multiple of the page size, the remaining memory is zeroed when mapped,
367 and writes to that region are not written out to the file.
368 The effect of
369 changing the size of the underlying file of a mapping on the pages that
370 correspond to added or removed regions of the file is unspecified.
371 .SS munmap()
372 The
373 .BR munmap ()
374 system call deletes the mappings for the specified address range, and
375 causes further references to addresses within the range to generate
376 invalid memory references.
377 The region is also automatically unmapped
378 when the process is terminated.
379 On the other hand, closing the file
380 descriptor does not unmap the region.
381 .LP
382 The address
383 .I addr
384 must be a multiple of the page size (but
385 .I length
386 need not be).
387 All pages containing a part
388 of the indicated range are unmapped, and subsequent references
389 to these pages will generate
390 .BR SIGSEGV .
391 It is not an error if the
392 indicated range does not contain any mapped pages.
393 .SH RETURN VALUE
394 On success,
395 .BR mmap ()
396 returns a pointer to the mapped area.
397 On error, the value
398 .B MAP_FAILED
399 (that is,
400 .IR "(void\ *)\ \-1" )
401 is returned, and
402 .I errno
403 is set to indicate the cause of the error.
404
405 On success,
406 .BR munmap ()
407 returns 0.
408 On failure, it returns \-1, and
409 .I errno
410 is set to indicate the cause of the error (probably to
411 .BR EINVAL ).
412 .SH ERRORS
413 .TP
414 .B EACCES
415 A file descriptor refers to a non-regular file.
416 Or a file mapping was requested, but
417 .I fd
418 is not open for reading.
419 Or
420 .B MAP_SHARED
421 was requested and
422 .B PROT_WRITE
423 is set, but
424 .I fd
425 is not open in read/write
426 .RB ( O_RDWR )
427 mode.
428 Or
429 .B PROT_WRITE
430 is set, but the file is append-only.
431 .TP
432 .B EAGAIN
433 The file has been locked, or too much memory has been locked (see
434 .BR setrlimit (2)).
435 .TP
436 .B EBADF
437 .I fd
438 is not a valid file descriptor (and
439 .B MAP_ANONYMOUS
440 was not set).
441 .TP
442 .B EINVAL
443 We don't like
444 .IR addr ,
445 .IR length ,
446 or
447 .I offset
448 (e.g., they are too large, or not aligned on a page boundary).
449 .TP
450 .B EINVAL
451 (since Linux 2.6.12)
452 .I length
453 was 0.
454 .TP
455 .B EINVAL
456 .I flags
457 contained neither
458 .B MAP_PRIVATE
459 or
460 .BR MAP_SHARED ,
461 or contained both of these values.
462 .TP
463 .B ENFILE
464 .\" This is for shared anonymous segments
465 .\" [2.6.7] shmem_zero_setup()-->shmem_file_setup()-->get_empty_filp()
466 The system-wide limit on the total number of open files has been reached.
467 .\" .TP
468 .\" .B ENOEXEC
469 .\" A file could not be mapped for reading.
470 .TP
471 .B ENODEV
472 The underlying filesystem of the specified file does not support
473 memory mapping.
474 .TP
475 .B ENOMEM
476 No memory is available.
477 .TP
478 .B ENOMEM
479 The process's maximum number of mappings would have been exceeded.
480 This error can also occur for
481 .BR munmap (2),
482 when unmapping a region in the middle of an existing mapping,
483 since this results in two smaller mappings on either side of
484 the region being unmapped.
485 .TP
486 .B EPERM
487 The
488 .I prot
489 argument asks for
490 .B PROT_EXEC
491 but the mapped area belongs to a file on a filesystem that
492 was mounted no-exec.
493 .\" (Since 2.4.25 / 2.6.0.)
494 .TP
495 .B EPERM
496 The operation was prevented by a file seal; see
497 .BR fcntl (2).
498 .TP
499 .B ETXTBSY
500 .B MAP_DENYWRITE
501 was set but the object specified by
502 .I fd
503 is open for writing.
504 .TP
505 .B EOVERFLOW
506 On 32-bit architecture together with the large file extension
507 (i.e., using 64-bit
508 .IR off_t ):
509 the number of pages used for
510 .I length
511 plus number of pages used for
512 .I offset
513 would overflow
514 .I "unsigned long"
515 (32 bits).
516 .LP
517 Use of a mapped region can result in these signals:
518 .TP
519 .B SIGSEGV
520 Attempted write into a region mapped as read-only.
521 .TP
522 .B SIGBUS
523 Attempted access to a portion of the buffer that does not correspond
524 to the file (for example, beyond the end of the file, including the
525 case where another process has truncated the file).
526 .SH ATTRIBUTES
527 For an explanation of the terms used in this section, see
528 .BR attributes (7).
529 .TS
530 allbox;
531 lbw18 lb lb
532 l l l.
533 Interface Attribute Value
534 T{
535 .BR mmap (),
536 .BR munmap ()
537 T} Thread safety MT-Safe
538 .TE
539 .SH CONFORMING TO
540 POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.
541 .\" SVr4 documents additional error codes ENXIO and ENODEV.
542 .\" SUSv2 documents additional error codes EMFILE and EOVERFLOW.
543 .SH AVAILABILITY
544 On POSIX systems on which
545 .BR mmap (),
546 .BR msync (2),
547 and
548 .BR munmap ()
549 are available,
550 .B _POSIX_MAPPED_FILES
551 is defined in \fI<unistd.h>\fP to a value greater than 0.
552 (See also
553 .BR sysconf (3).)
554 .\" POSIX.1-2001: It shall be defined to -1 or 0 or 200112L.
555 .\" -1: unavailable, 0: ask using sysconf().
556 .\" glibc defines it to 1.
557 .SH NOTES
558 On some hardware architectures (e.g., i386),
559 .B PROT_WRITE
560 implies
561 .BR PROT_READ .
562 It is architecture dependent whether
563 .B PROT_READ
564 implies
565 .B PROT_EXEC
566 or not.
567 Portable programs should always set
568 .B PROT_EXEC
569 if they intend to execute code in the new mapping.
570
571 The portable way to create a mapping is to specify
572 .I addr
573 as 0 (NULL), and omit
574 .B MAP_FIXED
575 from
576 .IR flags .
577 In this case, the system chooses the address for the mapping;
578 the address is chosen so as not to conflict with any existing mapping,
579 and will not be 0.
580 If the
581 .B MAP_FIXED
582 flag is specified, and
583 .I addr
584 is 0 (NULL), then the mapped address will be 0 (NULL).
585
586 Certain
587 .I flags
588 constants are defined only if suitable feature test macros are defined
589 (possibly by default):
590 .BR _DEFAULT_SOURCE
591 with glibc 2.19 or later;
592 or
593 .BR _BSD_SOURCE
594 or
595 .BR _SVID_SOURCE
596 in glibc 2.19 and earlier.
597 (Requiring
598 .BR _GNU_SOURCE
599 also suffices,
600 and requiring that macro specifically would have been more logical,
601 since these flags are all Linux-specific.)
602 The relevant flags are:
603 .BR MAP_32BIT ,
604 .BR MAP_ANONYMOUS
605 (and the synonym
606 .BR MAP_ANON ),
607 .BR MAP_DENYWRITE ,
608 .BR MAP_EXECUTABLE ,
609 .BR MAP_FILE ,
610 .BR MAP_GROWSDOWN ,
611 .BR MAP_HUGETLB ,
612 .BR MAP_LOCKED ,
613 .BR MAP_NONBLOCK ,
614 .BR MAP_NORESERVE ,
615 .BR MAP_POPULATE ,
616 and
617 .BR MAP_STACK .
618 .\"
619 .SS Timestamps changes for file-backed mappings
620 For file-backed mappings, the
621 .I st_atime
622 field for the mapped file may be updated at any time between the
623 .BR mmap ()
624 and the corresponding unmapping; the first reference to a mapped
625 page will update the field if it has not been already.
626 .LP
627 The
628 .I st_ctime
629 and
630 .I st_mtime
631 field for a file mapped with
632 .B PROT_WRITE
633 and
634 .B MAP_SHARED
635 will be updated after
636 a write to the mapped region, and before a subsequent
637 .BR msync (2)
638 with the
639 .B MS_SYNC
640 or
641 .B MS_ASYNC
642 flag, if one occurs.
643 .\"
644 .SS Huge page (Huge TLB) mappings
645 For mappings that employ huge pages, the requirements for the arguments of
646 .BR mmap ()
647 and
648 .BR munmap ()
649 differ somewhat from the requirements for mappings
650 that use the native system page size.
651
652 For
653 .BR mmap (),
654 .I offset
655 must be a multiple of the underlying huge page size.
656 The system automatically aligns
657 .I length
658 to be a multiple of the underlying huge page size.
659
660 For
661 .BR munmap (),
662 .I addr
663 and
664 .I length
665 must both be a multiple of the underlying huge page size.
666 .\"
667 .SS C library/kernel differences
668 This page describes the interface provided by the glibc
669 .BR mmap ()
670 wrapper function.
671 Originally, this function invoked a system call of the same name.
672 Since kernel 2.4, that system call has been superseded by
673 .BR mmap2 (2),
674 and nowadays
675 .\" Since around glibc 2.1/2.2, depending on the platform.
676 the glibc
677 .BR mmap ()
678 wrapper function invokes
679 .BR mmap2 (2)
680 with a suitably adjusted value for
681 .IR offset .
682 .SH BUGS
683 On Linux, there are no guarantees like those suggested above under
684 .BR MAP_NORESERVE .
685 By default, any process can be killed
686 at any moment when the system runs out of memory.
687
688 In kernels before 2.6.7, the
689 .B MAP_POPULATE
690 flag has effect only if
691 .I prot
692 is specified as
693 .BR PROT_NONE .
694
695 SUSv3 specifies that
696 .BR mmap ()
697 should fail if
698 .I length
699 is 0.
700 However, in kernels before 2.6.12,
701 .BR mmap ()
702 succeeded in this case: no mapping was created and the call returned
703 .IR addr .
704 Since kernel 2.6.12,
705 .BR mmap ()
706 fails with the error
707 .B EINVAL
708 for this case.
709
710 POSIX specifies that the system shall always
711 zero fill any partial page at the end
712 of the object and that system will never write any modification of the
713 object beyond its end.
714 On Linux, when you write data to such partial page after the end
715 of the object, the data stays in the page cache even after the file
716 is closed and unmapped
717 and even though the data is never written to the file itself,
718 subsequent mappings may see the modified content.
719 In some cases, this could be fixed by calling
720 .BR msync (2)
721 before the unmap takes place;
722 however, this doesn't work on tmpfs
723 (for example, when using POSIX shared memory interface documented in
724 .BR shm_overview (7)).
725 .SH EXAMPLE
726 .\" FIXME . Add an example here that uses an anonymous shared region for
727 .\" IPC between parent and child.
728 .PP
729 The following program prints part of the file specified in
730 its first command-line argument to standard output.
731 The range of bytes to be printed is specified via offset and length
732 values in the second and third command-line arguments.
733 The program creates a memory mapping of the required
734 pages of the file and then uses
735 .BR write (2)
736 to output the desired bytes.
737 .SS Program source
738 .nf
739 #include <sys/mman.h>
740 #include <sys/stat.h>
741 #include <fcntl.h>
742 #include <stdio.h>
743 #include <stdlib.h>
744 #include <unistd.h>
745
746 #define handle_error(msg) \\
747 do { perror(msg); exit(EXIT_FAILURE); } while (0)
748
749 int
750 main(int argc, char *argv[])
751 {
752 char *addr;
753 int fd;
754 struct stat sb;
755 off_t offset, pa_offset;
756 size_t length;
757 ssize_t s;
758
759 if (argc < 3 || argc > 4) {
760 fprintf(stderr, "%s file offset [length]\\n", argv[0]);
761 exit(EXIT_FAILURE);
762 }
763
764 fd = open(argv[1], O_RDONLY);
765 if (fd == \-1)
766 handle_error("open");
767
768 if (fstat(fd, &sb) == \-1) /* To obtain file size */
769 handle_error("fstat");
770
771 offset = atoi(argv[2]);
772 pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) \- 1);
773 /* offset for mmap() must be page aligned */
774
775 if (offset >= sb.st_size) {
776 fprintf(stderr, "offset is past end of file\\n");
777 exit(EXIT_FAILURE);
778 }
779
780 if (argc == 4) {
781 length = atoi(argv[3]);
782 if (offset + length > sb.st_size)
783 length = sb.st_size \- offset;
784 /* Can\(aqt display bytes past end of file */
785
786 } else { /* No length arg ==> display to end of file */
787 length = sb.st_size \- offset;
788 }
789
790 addr = mmap(NULL, length + offset \- pa_offset, PROT_READ,
791 MAP_PRIVATE, fd, pa_offset);
792 if (addr == MAP_FAILED)
793 handle_error("mmap");
794
795 s = write(STDOUT_FILENO, addr + offset \- pa_offset, length);
796 if (s != length) {
797 if (s == \-1)
798 handle_error("write");
799
800 fprintf(stderr, "partial write");
801 exit(EXIT_FAILURE);
802 }
803
804 munmap(addr, length + offset \- pa_offset);
805 close(fd);
806
807 exit(EXIT_SUCCESS);
808 }
809 .fi
810 .SH SEE ALSO
811 .BR getpagesize (2),
812 .BR memfd_create (2),
813 .BR mincore (2),
814 .BR mlock (2),
815 .BR mmap2 (2),
816 .BR mprotect (2),
817 .BR mremap (2),
818 .BR msync (2),
819 .BR remap_file_pages (2),
820 .BR setrlimit (2),
821 .BR shmat (2),
822 .BR shm_open (3),
823 .BR shm_overview (7)
824
825 The descriptions of the following files in
826 .BR proc (5):
827 .IR /proc/[pid]/maps ,
828 .IR /proc/[pid]/map_files ,
829 and
830 .IR /proc/[pid]/smaps .
831
832 B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128-129 and 389-391.
833 .\"
834 .\" Repeat after me: private read-only mappings are 100% equivalent to
835 .\" shared read-only mappings. No ifs, buts, or maybes. -- Linus