mmap.2: wfix
[man-pages.git] / man2 / mmap.2
blobd1942b52ac9cb0df3e6fa2805d70be0ef4ad0fe2
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 2017-05-03 "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
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.
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.
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.
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.
101 .B PROT_READ
102 Pages may be read.
104 .B PROT_WRITE
105 Pages may be written.
107 .B PROT_NONE
108 Pages may not be accessed.
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 :
119 .B MAP_SHARED
120 Share this mapping.
121 Updates to the mapping are visible to other processes mapping the same region,
122 and (in the case of file-backed mappings)
123 are carried through to the underlying file.
124 (To precisely control when updates are carried through
125 to the underlying file requires the use of
126 .BR msync (2).)
128 .B MAP_PRIVATE
129 Create a private copy-on-write mapping.
130 Updates to the mapping are not visible to other processes
131 mapping the same file, and are not carried through to
132 the underlying file.
133 It is unspecified whether changes made to the file after the
134 .BR mmap ()
135 call are visible in the mapped region.
137 Both of these flags are described in POSIX.1-2001 and POSIX.1-2008.
139 In addition, zero or more of the following values can be ORed in
140 .IR flags :
142 .BR MAP_32BIT " (since Linux 2.4.20, 2.6)"
143 Put the mapping into the first 2 Gigabytes of the process address space.
144 This flag is supported only on x86-64, for 64-bit programs.
145 It was added to allow thread stacks to be allocated somewhere
146 in the first 2GB of memory,
147 so as to improve context-switch performance on some early
148 64-bit processors.
149 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
150 Modern x86-64 processors no longer have this performance problem,
151 so use of this flag is not required on those systems.
153 .B MAP_32BIT
154 flag is ignored when
155 .B MAP_FIXED
156 is set.
158 .B MAP_ANON
159 Synonym for
160 .BR MAP_ANONYMOUS .
161 Deprecated.
163 .B MAP_ANONYMOUS
164 The mapping is not backed by any file;
165 its contents are initialized to zero.
167 .I fd
168 argument is ignored;
169 however, some implementations require
170 .I fd
171 to be \-1 if
172 .B MAP_ANONYMOUS
174 .BR MAP_ANON )
175 is specified,
176 and portable applications should ensure this.
178 .I offset
179 argument should be zero.
180 .\" See the pgoff overflow check in do_mmap().
181 .\" See the offset check in sys_mmap in arch/x86/kernel/sys_x86_64.c.
182 The use of
183 .B MAP_ANONYMOUS
184 in conjunction with
185 .B MAP_SHARED
186 is supported on Linux only since kernel 2.4.
188 .B MAP_DENYWRITE
189 This flag is ignored.
190 .\" Introduced in 1.1.36, removed in 1.3.24.
191 (Long ago, it signaled that attempts to write to the underlying file
192 should fail with
193 .BR ETXTBUSY .
194 But this was a source of denial-of-service attacks.)
196 .B MAP_EXECUTABLE
197 This flag is ignored.
198 .\" Introduced in 1.1.38, removed in 1.3.24. Flag tested in proc_follow_link.
199 .\" (Long ago, it signaled that the underlying file is an executable.
200 .\" However, that information was not really used anywhere.)
201 .\" Linus talked about DOS related to MAP_EXECUTABLE, but he was thinking of
202 .\" MAP_DENYWRITE?
204 .B MAP_FILE
205 Compatibility flag.
206 Ignored.
207 .\" On some systems, this was required as the opposite of
208 .\" MAP_ANONYMOUS -- mtk, 1 May 2007
210 .B MAP_FIXED
211 Don't interpret
212 .I addr
213 as a hint: place the mapping at exactly that address.
214 .I addr
215 must be a multiple of the page size.
216 If the memory region specified by
217 .I addr
219 .I len
220 overlaps pages of any existing mapping(s), then the overlapped
221 part of the existing mapping(s) will be discarded.
222 If the specified address cannot be used,
223 .BR mmap ()
224 will fail.
225 Because requiring a fixed address for a mapping is less portable,
226 the use of this option is discouraged.
228 .B MAP_GROWSDOWN
229 This flag is used for stacks.
230 It indicates to the kernel virtual memory system that the mapping
231 should extend downward in memory.
232 The return address is one page lower than the memory area that is
233 actually created in the process's virtual address space.
234 Touching an address in the "guard" page below the mapping will cause
235 the mapping to grow by a page.
236 This growth can be repeated until the mapping grows to within a
237 page of the high end of the next lower mapping,
238 at which point touching the "guard" page will result in a
239 .B SIGSEGV
240 signal.
242 .BR MAP_HUGETLB " (since Linux 2.6.32)"
243 Allocate the mapping using "huge pages."
244 See the Linux kernel source file
245 .I Documentation/vm/hugetlbpage.txt
246 for further information, as well as NOTES, below.
248 .BR MAP_HUGE_2MB ", " MAP_HUGE_1GB " (since Linux 3.8)"
249 .\" See https://lwn.net/Articles/533499/
250 Used in conjunction with
251 .B MAP_HUGETLB
252 to select alternative hugetlb page sizes (respectively, 2 MB and 1 GB)
253 on systems that support multiple hugetlb page sizes.
255 More generally, the desired huge page size can be configured by encoding
256 the base-2 logarithm of the desired page size in the six bits at the offset
257 .BR MAP_HUGE_SHIFT .
258 (A value of zero in this bit field provides the default huge page size;
259 the default huge page size can be discovered vie the
260 .I Hugepagesize
261 field exposed by
262 .IR /proc/meminfo .)
263 Thus, the above two constants are defined as:
266 .in +4n
267 #define MAP_HUGE_2MB    (21 << MAP_HUGE_SHIFT)
268 #define MAP_HUGE_1GB    (30 << MAP_HUGE_SHIFT)
272 The range of huge page sizes that are supported by the system
273 can be discovered by listing the subdirectories in
274 .IR /sys/kernel/mm/hugepages .
276 .BR MAP_LOCKED " (since Linux 2.5.37)"
277 Mark the mmaped region to be locked in the same way as
278 .BR mlock (2).
279 This implementation will try to populate (prefault) the whole range but
280 the mmap call doesn't fail with
281 .B ENOMEM
282 if this fails.
283 Therefore major faults might happen later on.
284 So the semantic is not as strong as
285 .BR mlock (2).
286 One should use
287 .BR mmap ()
288 plus
289 .BR mlock (2)
290 when major faults are not acceptable after the initialization of the mapping.
292 .BR MAP_LOCKED
293 flag is ignored in older kernels.
294 .\" If set, the mapped pages will not be swapped out.
296 .BR MAP_NONBLOCK " (since Linux 2.5.46)"
297 This flag is meaningful only in conjunction with
298 .BR MAP_POPULATE .
299 Don't perform read-ahead:
300 create page tables entries only for pages
301 that are already present in RAM.
302 Since Linux 2.6.23, this flag causes
303 .BR MAP_POPULATE
304 to do nothing.
305 One day, the combination of
306 .BR MAP_POPULATE
308 .BR MAP_NONBLOCK
309 may be reimplemented.
311 .B MAP_NORESERVE
312 Do not reserve swap space for this mapping.
313 When swap space is reserved, one has the guarantee
314 that it is possible to modify the mapping.
315 When swap space is not reserved one might get
316 .B SIGSEGV
317 upon a write
318 if no physical memory is available.
319 See also the discussion of the file
320 .I /proc/sys/vm/overcommit_memory
322 .BR proc (5).
323 In kernels before 2.6, this flag had effect only for
324 private writable mappings.
326 .BR MAP_POPULATE " (since Linux 2.5.46)"
327 Populate (prefault) page tables for a mapping.
328 For a file mapping, this causes read-ahead on the file.
329 This will help to reduce blocking on page faults later.
330 .BR MAP_POPULATE
331 is supported for private mappings only since Linux 2.6.23.
333 .BR MAP_STACK " (since Linux 2.6.27)"
334 Allocate the mapping at an address suitable for a process
335 or thread stack.
336 This flag is currently a no-op,
337 but is used in the glibc threading implementation so that
338 if some architectures require special treatment for stack allocations,
339 support can later be transparently implemented for glibc.
340 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
341 .\" commit cd98a04a59e2f94fa64d5bf1e26498d27427d5e7
342 .\" http://thread.gmane.org/gmane.linux.kernel/720412
343 .\" "pthread_create() slow for many threads; also time to revisit 64b
344 .\"  context switch optimization?"
346 .BR MAP_UNINITIALIZED " (since Linux 2.6.33)"
347 Don't clear anonymous pages.
348 This flag is intended to improve performance on embedded devices.
349 This flag is honored only if the kernel was configured with the
350 .B CONFIG_MMAP_ALLOW_UNINITIALIZED
351 option.
352 Because of the security implications,
353 that option is normally enabled only on embedded devices
354 (i.e., devices where one has complete control of the contents of user memory).
356 Of the above flags, only
357 .B MAP_FIXED
358 is specified in POSIX.1-2001 and POSIX.1-2008.
359 However, most systems also support
360 .B MAP_ANONYMOUS
361 (or its synonym
362 .BR MAP_ANON ).
363 .\" FIXME . for later review when Issue 8 is one day released...
364 .\" POSIX may add MAP_ANON in the future
365 .\" http://austingroupbugs.net/tag_view_page.php?tag_id=8
366 .\" http://austingroupbugs.net/view.php?id=850
368 Memory mapped by
369 .BR mmap ()
370 is preserved across
371 .BR fork (2),
372 with the same attributes.
374 A file is mapped in multiples of the page size.
375 For a file that is not
376 a multiple of the page size, the remaining memory is zeroed when mapped,
377 and writes to that region are not written out to the file.
378 The effect of
379 changing the size of the underlying file of a mapping on the pages that
380 correspond to added or removed regions of the file is unspecified.
381 .SS munmap()
383 .BR munmap ()
384 system call deletes the mappings for the specified address range, and
385 causes further references to addresses within the range to generate
386 invalid memory references.
387 The region is also automatically unmapped
388 when the process is terminated.
389 On the other hand, closing the file
390 descriptor does not unmap the region.
392 The address
393 .I addr
394 must be a multiple of the page size (but
395 .I length
396 need not be).
397 All pages containing a part
398 of the indicated range are unmapped, and subsequent references
399 to these pages will generate
400 .BR SIGSEGV .
401 It is not an error if the
402 indicated range does not contain any mapped pages.
403 .SH RETURN VALUE
404 On success,
405 .BR mmap ()
406 returns a pointer to the mapped area.
407 On error, the value
408 .B MAP_FAILED
409 (that is,
410 .IR "(void\ *)\ \-1" )
411 is returned, and
412 .I errno
413 is set to indicate the cause of the error.
415 On success,
416 .BR munmap ()
417 returns 0.
418 On failure, it returns \-1, and
419 .I errno
420 is set to indicate the cause of the error (probably to
421 .BR EINVAL ).
422 .SH ERRORS
424 .B EACCES
425 A file descriptor refers to a non-regular file.
426 Or a file mapping was requested, but
427 .I fd
428 is not open for reading.
430 .B MAP_SHARED
431 was requested and
432 .B PROT_WRITE
433 is set, but
434 .I fd
435 is not open in read/write
436 .RB ( O_RDWR )
437 mode.
439 .B PROT_WRITE
440 is set, but the file is append-only.
442 .B EAGAIN
443 The file has been locked, or too much memory has been locked (see
444 .BR setrlimit (2)).
446 .B EBADF
447 .I fd
448 is not a valid file descriptor (and
449 .B MAP_ANONYMOUS
450 was not set).
452 .B EINVAL
453 We don't like
454 .IR addr ,
455 .IR length ,
457 .I offset
458 (e.g., they are too large, or not aligned on a page boundary).
460 .B EINVAL
461 (since Linux 2.6.12)
462 .I length
463 was 0.
465 .B EINVAL
466 .I flags
467 contained neither
468 .B MAP_PRIVATE
470 .BR MAP_SHARED ,
471 or contained both of these values.
473 .B ENFILE
474 .\" This is for shared anonymous segments
475 .\" [2.6.7] shmem_zero_setup()-->shmem_file_setup()-->get_empty_filp()
476 The system-wide limit on the total number of open files has been reached.
477 .\" .TP
478 .\" .B ENOEXEC
479 .\" A file could not be mapped for reading.
481 .B ENODEV
482 The underlying filesystem of the specified file does not support
483 memory mapping.
485 .B ENOMEM
486 No memory is available.
488 .B ENOMEM
489 The process's maximum number of mappings would have been exceeded.
490 This error can also occur for
491 .BR munmap (),
492 when unmapping a region in the middle of an existing mapping,
493 since this results in two smaller mappings on either side of
494 the region being unmapped.
496 .B EOVERFLOW
497 On 32-bit architecture together with the large file extension
498 (i.e., using 64-bit
499 .IR off_t ):
500 the number of pages used for
501 .I length
502 plus number of pages used for
503 .I offset
504 would overflow
505 .I "unsigned long"
506 (32 bits).
508 .B EPERM
510 .I prot
511 argument asks for
512 .B PROT_EXEC
513 but the mapped area belongs to a file on a filesystem that
514 was mounted no-exec.
515 .\" (Since 2.4.25 / 2.6.0.)
517 .B EPERM
518 The operation was prevented by a file seal; see
519 .BR fcntl (2).
521 .B ETXTBSY
522 .B MAP_DENYWRITE
523 was set but the object specified by
524 .I fd
525 is open for writing.
527 Use of a mapped region can result in these signals:
529 .B SIGSEGV
530 Attempted write into a region mapped as read-only.
532 .B SIGBUS
533 Attempted access to a portion of the buffer that does not correspond
534 to the file (for example, beyond the end of the file, including the
535 case where another process has truncated the file).
536 .SH ATTRIBUTES
537 For an explanation of the terms used in this section, see
538 .BR attributes (7).
540 allbox;
541 lbw18 lb lb
542 l l l.
543 Interface       Attribute       Value
545 .BR mmap (),
546 .BR munmap ()
547 T}      Thread safety   MT-Safe
549 .SH CONFORMING TO
550 POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.
551 .\" SVr4 documents additional error codes ENXIO and ENODEV.
552 .\" SUSv2 documents additional error codes EMFILE and EOVERFLOW.
553 .SH AVAILABILITY
554 On POSIX systems on which
555 .BR mmap (),
556 .BR msync (2),
558 .BR munmap ()
559 are available,
560 .B _POSIX_MAPPED_FILES
561 is defined in \fI<unistd.h>\fP to a value greater than 0.
562 (See also
563 .BR sysconf (3).)
564 .\" POSIX.1-2001: It shall be defined to -1 or 0 or 200112L.
565 .\" -1: unavailable, 0: ask using sysconf().
566 .\" glibc defines it to 1.
567 .SH NOTES
568 On some hardware architectures (e.g., i386),
569 .B PROT_WRITE
570 implies
571 .BR PROT_READ .
572 It is architecture dependent whether
573 .B PROT_READ
574 implies
575 .B PROT_EXEC
576 or not.
577 Portable programs should always set
578 .B PROT_EXEC
579 if they intend to execute code in the new mapping.
581 The portable way to create a mapping is to specify
582 .I addr
583 as 0 (NULL), and omit
584 .B MAP_FIXED
585 from
586 .IR flags .
587 In this case, the system chooses the address for the mapping;
588 the address is chosen so as not to conflict with any existing mapping,
589 and will not be 0.
590 If the
591 .B MAP_FIXED
592 flag is specified, and
593 .I addr
594 is 0 (NULL), then the mapped address will be 0 (NULL).
596 Certain
597 .I flags
598 constants are defined only if suitable feature test macros are defined
599 (possibly by default):
600 .BR _DEFAULT_SOURCE
601 with glibc 2.19 or later;
603 .BR _BSD_SOURCE
605 .BR _SVID_SOURCE
606 in glibc 2.19 and earlier.
607 (Employing
608 .BR _GNU_SOURCE
609 also suffices,
610 and requiring that macro specifically would have been more logical,
611 since these flags are all Linux-specific.)
612 The relevant flags are:
613 .BR MAP_32BIT ,
614 .BR MAP_ANONYMOUS
615 (and the synonym
616 .BR MAP_ANON ),
617 .BR MAP_DENYWRITE ,
618 .BR MAP_EXECUTABLE ,
619 .BR MAP_FILE ,
620 .BR MAP_GROWSDOWN ,
621 .BR MAP_HUGETLB ,
622 .BR MAP_LOCKED ,
623 .BR MAP_NONBLOCK ,
624 .BR MAP_NORESERVE ,
625 .BR MAP_POPULATE ,
627 .BR MAP_STACK .
629 An application can determine which pages of a mapping are
630 currently resident in the buffer/page cache using
631 .BR mincore (2).
633 .SS Timestamps changes for file-backed mappings
634 For file-backed mappings, the
635 .I st_atime
636 field for the mapped file may be updated at any time between the
637 .BR mmap ()
638 and the corresponding unmapping; the first reference to a mapped
639 page will update the field if it has not been already.
642 .I st_ctime
644 .I st_mtime
645 field for a file mapped with
646 .B PROT_WRITE
648 .B MAP_SHARED
649 will be updated after
650 a write to the mapped region, and before a subsequent
651 .BR msync (2)
652 with the
653 .B MS_SYNC
655 .B MS_ASYNC
656 flag, if one occurs.
658 .SS Huge page (Huge TLB) mappings
659 For mappings that employ huge pages, the requirements for the arguments of
660 .BR mmap ()
662 .BR munmap ()
663 differ somewhat from the requirements for mappings
664 that use the native system page size.
667 .BR mmap (),
668 .I offset
669 must be a multiple of the underlying huge page size.
670 The system automatically aligns
671 .I length
672 to be a multiple of the underlying huge page size.
675 .BR munmap (),
676 .I addr
678 .I length
679 must both be a multiple of the underlying huge page size.
681 .SS C library/kernel differences
682 This page describes the interface provided by the glibc
683 .BR mmap ()
684 wrapper function.
685 Originally, this function invoked a system call of the same name.
686 Since kernel 2.4, that system call has been superseded by
687 .BR mmap2 (2),
688 and nowadays
689 .\" Since around glibc 2.1/2.2, depending on the platform.
690 the glibc
691 .BR mmap ()
692 wrapper function invokes
693 .BR mmap2 (2)
694 with a suitably adjusted value for
695 .IR offset .
696 .SH BUGS
697 On Linux, there are no guarantees like those suggested above under
698 .BR MAP_NORESERVE .
699 By default, any process can be killed
700 at any moment when the system runs out of memory.
702 In kernels before 2.6.7, the
703 .B MAP_POPULATE
704 flag has effect only if
705 .I prot
706 is specified as
707 .BR PROT_NONE .
709 SUSv3 specifies that
710 .BR mmap ()
711 should fail if
712 .I length
713 is 0.
714 However, in kernels before 2.6.12,
715 .BR mmap ()
716 succeeded in this case: no mapping was created and the call returned
717 .IR addr .
718 Since kernel 2.6.12,
719 .BR mmap ()
720 fails with the error
721 .B EINVAL
722 for this case.
724 POSIX specifies that the system shall always
725 zero fill any partial page at the end
726 of the object and that system will never write any modification of the
727 object beyond its end.
728 On Linux, when you write data to such partial page after the end
729 of the object, the data stays in the page cache even after the file
730 is closed and unmapped
731 and even though the data is never written to the file itself,
732 subsequent mappings may see the modified content.
733 In some cases, this could be fixed by calling
734 .BR msync (2)
735 before the unmap takes place;
736 however, this doesn't work on
737 .BR tmpfs (5)
738 (for example, when using the POSIX shared memory interface documented in
739 .BR shm_overview (7)).
740 .SH EXAMPLE
741 .\" FIXME . Add an example here that uses an anonymous shared region for
742 .\" IPC between parent and child.
744 The following program prints part of the file specified in
745 its first command-line argument to standard output.
746 The range of bytes to be printed is specified via offset and length
747 values in the second and third command-line arguments.
748 The program creates a memory mapping of the required
749 pages of the file and then uses
750 .BR write (2)
751 to output the desired bytes.
752 .SS Program source
754 #include <sys/mman.h>
755 #include <sys/stat.h>
756 #include <fcntl.h>
757 #include <stdio.h>
758 #include <stdlib.h>
759 #include <unistd.h>
761 #define handle_error(msg) \\
762     do { perror(msg); exit(EXIT_FAILURE); } while (0)
765 main(int argc, char *argv[])
767     char *addr;
768     int fd;
769     struct stat sb;
770     off_t offset, pa_offset;
771     size_t length;
772     ssize_t s;
774     if (argc < 3 || argc > 4) {
775         fprintf(stderr, "%s file offset [length]\\n", argv[0]);
776         exit(EXIT_FAILURE);
777     }
779     fd = open(argv[1], O_RDONLY);
780     if (fd == \-1)
781         handle_error("open");
783     if (fstat(fd, &sb) == \-1)           /* To obtain file size */
784         handle_error("fstat");
786     offset = atoi(argv[2]);
787     pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) \- 1);
788         /* offset for mmap() must be page aligned */
790     if (offset >= sb.st_size) {
791         fprintf(stderr, "offset is past end of file\\n");
792         exit(EXIT_FAILURE);
793     }
795     if (argc == 4) {
796         length = atoi(argv[3]);
797         if (offset + length > sb.st_size)
798             length = sb.st_size \- offset;
799                 /* Can\(aqt display bytes past end of file */
801     } else {    /* No length arg ==> display to end of file */
802         length = sb.st_size \- offset;
803     }
805     addr = mmap(NULL, length + offset \- pa_offset, PROT_READ,
806                 MAP_PRIVATE, fd, pa_offset);
807     if (addr == MAP_FAILED)
808         handle_error("mmap");
810     s = write(STDOUT_FILENO, addr + offset \- pa_offset, length);
811     if (s != length) {
812         if (s == \-1)
813             handle_error("write");
815         fprintf(stderr, "partial write");
816         exit(EXIT_FAILURE);
817     }
819     munmap(addr, length + offset \- pa_offset);
820     close(fd);
822     exit(EXIT_SUCCESS);
825 .SH SEE ALSO
826 .BR getpagesize (2),
827 .BR memfd_create (2),
828 .BR mincore (2),
829 .BR mlock (2),
830 .BR mmap2 (2),
831 .BR mprotect (2),
832 .BR mremap (2),
833 .BR msync (2),
834 .BR remap_file_pages (2),
835 .BR setrlimit (2),
836 .BR shmat (2),
837 .BR userfaultfd (2),
838 .BR shm_open (3),
839 .BR shm_overview (7)
841 The descriptions of the following files in
842 .BR proc (5):
843 .IR /proc/[pid]/maps ,
844 .IR /proc/[pid]/map_files ,
846 .IR /proc/[pid]/smaps .
848 B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128-129 and 389-391.
850 .\" Repeat after me: private read-only mappings are 100% equivalent to
851 .\" shared read-only mappings. No ifs, buts, or maybes. -- Linus