1MMAP(2)                    Linux Programmer's Manual                   MMAP(2)
2
3
4

NAME

6       mmap, munmap - map or unmap files or devices into memory
7

SYNOPSIS

9       #include <sys/mman.h>
10
11       void *mmap(void *addr, size_t length, int prot, int flags,
12                  int fd, off_t offset);
13       int munmap(void *addr, size_t length);
14
15       See NOTES for information on feature test macro requirements.
16

DESCRIPTION

18       mmap()  creates a new mapping in the virtual address space of the call‐
19       ing process.  The starting address for the new mapping is specified  in
20       addr.   The  length argument specifies the length of the mapping (which
21       must be greater than 0).
22
23       If addr is NULL, then the kernel chooses the (page-aligned) address  at
24       which to create the mapping; this is the most portable method of creat‐
25       ing a new mapping.  If addr is not NULL, then the kernel takes it as  a
26       hint about where to place the mapping; on Linux, the kernel will pick a
27       nearby page boundary (but always above or equal to the value  specified
28       by /proc/sys/vm/mmap_min_addr) and attempt to create the mapping there.
29       If another mapping already exists there, the kernel picks a new address
30       that may or may not depend on the hint.  The address of the new mapping
31       is returned as the result of the call.
32
33       The contents of a file mapping (as opposed to an anonymous mapping; see
34       MAP_ANONYMOUS  below),  are  initialized using length bytes starting at
35       offset offset in the file (or other object) referred to by the file de‐
36       scriptor fd.  offset must be a multiple of the page size as returned by
37       sysconf(_SC_PAGE_SIZE).
38
39       After the mmap() call has returned, the file  descriptor,  fd,  can  be
40       closed immediately without invalidating the mapping.
41
42       The  prot  argument describes the desired memory protection of the map‐
43       ping (and must not conflict with the open mode of the file).  It is ei‐
44       ther PROT_NONE or the bitwise OR of one or more of the following flags:
45
46       PROT_EXEC  Pages may be executed.
47
48       PROT_READ  Pages may be read.
49
50       PROT_WRITE Pages may be written.
51
52       PROT_NONE  Pages may not be accessed.
53
54   The flags argument
55       The  flags argument determines whether updates to the mapping are visi‐
56       ble to other processes mapping the same region, and whether updates are
57       carried through to the underlying file.  This behavior is determined by
58       including exactly one of the following values in flags:
59
60       MAP_SHARED
61              Share this mapping.  Updates to the mapping are visible to other
62              processes  mapping  the  same  region, and (in the case of file-
63              backed mappings) are carried through  to  the  underlying  file.
64              (To  precisely  control  when updates are carried through to the
65              underlying file requires the use of msync(2).)
66
67       MAP_SHARED_VALIDATE (since Linux 4.15)
68              This flag provides the same behavior as MAP_SHARED  except  that
69              MAP_SHARED mappings ignore unknown flags in flags.  By contrast,
70              when creating a mapping using  MAP_SHARED_VALIDATE,  the  kernel
71              verifies  all  passed flags are known and fails the mapping with
72              the error EOPNOTSUPP for unknown flags.  This  mapping  type  is
73              also  required  to  be  able  to  use  some mapping flags (e.g.,
74              MAP_SYNC).
75
76       MAP_PRIVATE
77              Create a private copy-on-write mapping.  Updates to the  mapping
78              are  not  visible  to other processes mapping the same file, and
79              are not carried through to the underlying file.  It is  unspeci‐
80              fied  whether changes made to the file after the mmap() call are
81              visible in the mapped region.
82
83       Both MAP_SHARED and  MAP_PRIVATE  are  described  in  POSIX.1-2001  and
84       POSIX.1-2008.  MAP_SHARED_VALIDATE is a Linux extension.
85
86       In addition, zero or more of the following values can be ORed in flags:
87
88       MAP_32BIT (since Linux 2.4.20, 2.6)
89              Put  the  mapping  into the first 2 Gigabytes of the process ad‐
90              dress space.  This flag is supported only on x86-64, for  64-bit
91              programs.   It  was added to allow thread stacks to be allocated
92              somewhere in the first 2 GB of memory, so as to improve context-
93              switch  performance  on  some  early  64-bit processors.  Modern
94              x86-64 processors no longer have this  performance  problem,  so
95              use  of  this  flag  is  not  required  on  those  systems.  The
96              MAP_32BIT flag is ignored when MAP_FIXED is set.
97
98       MAP_ANON
99              Synonym for MAP_ANONYMOUS; provided for compatibility with other
100              implementations.
101
102       MAP_ANONYMOUS
103              The mapping is not backed by any file; its contents are initial‐
104              ized to zero.  The fd argument is ignored; however, some  imple‐
105              mentations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is
106              specified, and portable applications should  ensure  this.   The
107              offset  argument  should  be  zero.  The use of MAP_ANONYMOUS in
108              conjunction with MAP_SHARED is supported  on  Linux  only  since
109              kernel 2.4.
110
111       MAP_DENYWRITE
112              This  flag  is ignored.  (Long ago—Linux 2.0 and earlier—it sig‐
113              naled that attempts to write to the underlying file should  fail
114              with  ETXTBSY.   But  this was a source of denial-of-service at‐
115              tacks.)
116
117       MAP_EXECUTABLE
118              This flag is ignored.
119
120       MAP_FILE
121              Compatibility flag.  Ignored.
122
123       MAP_FIXED
124              Don't interpret addr as a hint: place  the  mapping  at  exactly
125              that address.  addr must be suitably aligned: for most architec‐
126              tures a multiple of the page size is sufficient;  however,  some
127              architectures may impose additional restrictions.  If the memory
128              region specified by addr and len overlaps pages of any  existing
129              mapping(s),  then the overlapped part of the existing mapping(s)
130              will be discarded.  If the specified  address  cannot  be  used,
131              mmap() will fail.
132
133              Software  that  aspires  to be portable should use the MAP_FIXED
134              flag with care, keeping in mind  that  the  exact  layout  of  a
135              process's memory mappings is allowed to change significantly be‐
136              tween kernel versions, C library versions, and operating  system
137              releases.  Carefully read the discussion of this flag in NOTES!
138
139       MAP_FIXED_NOREPLACE (since Linux 4.17)
140              This  flag  provides  behavior that is similar to MAP_FIXED with
141              respect  to  the  addr  enforcement,   but   differs   in   that
142              MAP_FIXED_NOREPLACE  never  clobbers a preexisting mapped range.
143              If the requested range would collide with an  existing  mapping,
144              then  this  call  fails  with  the  error EEXIST.  This flag can
145              therefore be used as a way to atomically (with respect to  other
146              threads)  attempt  to map an address range: one thread will suc‐
147              ceed; all others will report failure.
148
149              Note  that  older   kernels   which   do   not   recognize   the
150              MAP_FIXED_NOREPLACE flag will typically (upon detecting a colli‐
151              sion with a preexisting mapping) fall back to a  "non-MAP_FIXED"
152              type  of behavior: they will return an address that is different
153              from  the  requested  address.   Therefore,  backward-compatible
154              software should check the returned address against the requested
155              address.
156
157       MAP_GROWSDOWN
158              This flag is used for stacks.  It indicates to the  kernel  vir‐
159              tual  memory  system  that the mapping should extend downward in
160              memory.  The return address is one page lower  than  the  memory
161              area  that  is actually created in the process's virtual address
162              space.  Touching an address in the "guard" page below  the  map‐
163              ping  will cause the mapping to grow by a page.  This growth can
164              be repeated until the mapping grows to within a page of the high
165              end  of  the  next  lower  mapping,  at which point touching the
166              "guard" page will result in a SIGSEGV signal.
167
168       MAP_HUGETLB (since Linux 2.6.32)
169              Allocate the mapping using "huge" pages.  See the  Linux  kernel
170              source   file  Documentation/admin-guide/mm/hugetlbpage.rst  for
171              further information, as well as NOTES, below.
172
173       MAP_HUGE_2MB, MAP_HUGE_1GB (since Linux 3.8)
174              Used in  conjunction  with  MAP_HUGETLB  to  select  alternative
175              hugetlb page sizes (respectively, 2 MB and 1 GB) on systems that
176              support multiple hugetlb page sizes.
177
178              More generally, the desired huge page size can be configured  by
179              encoding  the  base-2  logarithm of the desired page size in the
180              six bits at the offset MAP_HUGE_SHIFT.  (A value of zero in this
181              bit  field provides the default huge page size; the default huge
182              page size can be discovered via the Hugepagesize  field  exposed
183              by  /proc/meminfo.)   Thus,  the above two constants are defined
184              as:
185
186                  #define MAP_HUGE_2MB    (21 << MAP_HUGE_SHIFT)
187                  #define MAP_HUGE_1GB    (30 << MAP_HUGE_SHIFT)
188
189              The range of huge page sizes that are supported  by  the  system
190              can  be  discovered  by  listing the subdirectories in /sys/ker‐
191              nel/mm/hugepages.
192
193       MAP_LOCKED (since Linux 2.5.37)
194              Mark the mapped region to be locked in the same way as mlock(2).
195              This  implementation  will  try to populate (prefault) the whole
196              range but the mmap() call  doesn't  fail  with  ENOMEM  if  this
197              fails.   Therefore  major  faults might happen later on.  So the
198              semantic is not as strong as mlock(2).  One  should  use  mmap()
199              plus  mlock(2)  when  major  faults are not acceptable after the
200              initialization of the mapping.  The MAP_LOCKED flag  is  ignored
201              in older kernels.
202
203       MAP_NONBLOCK (since Linux 2.5.46)
204              This  flag  is meaningful only in conjunction with MAP_POPULATE.
205              Don't perform read-ahead: create page tables  entries  only  for
206              pages that are already present in RAM.  Since Linux 2.6.23, this
207              flag causes MAP_POPULATE to do nothing.  One day,  the  combina‐
208              tion of MAP_POPULATE and MAP_NONBLOCK may be reimplemented.
209
210       MAP_NORESERVE
211              Do  not reserve swap space for this mapping.  When swap space is
212              reserved, one has the guarantee that it is  possible  to  modify
213              the  mapping.   When  swap  space  is not reserved one might get
214              SIGSEGV upon a write if no physical memory  is  available.   See
215              also  the  discussion of the file /proc/sys/vm/overcommit_memory
216              in proc(5).  In kernels before 2.6, this flag  had  effect  only
217              for private writable mappings.
218
219       MAP_POPULATE (since Linux 2.5.46)
220              Populate  (prefault) page tables for a mapping.  For a file map‐
221              ping, this causes read-ahead on the file.  This will help to re‐
222              duce  blocking  on  page  faults later.  The mmap() call doesn't
223              fail if the mapping cannot be populated  (for  example,  due  to
224              limitations  on  the  number  of  mapped  huge  pages when using
225              MAP_HUGETLB).  MAP_POPULATE is supported  for  private  mappings
226              only since Linux 2.6.23.
227
228       MAP_STACK (since Linux 2.6.27)
229              Allocate  the  mapping  at  an address suitable for a process or
230              thread stack.
231
232              This flag is currently a no-op on Linux.  However, by  employing
233              this  flag,  applications can ensure that they transparently ob‐
234              tain support if the flag is implemented in the future.  Thus, it
235              is  used  in the glibc threading implementation to allow for the
236              fact that some architectures may (later) require special  treat‐
237              ment  for  stack  allocations.   A further reason to employ this
238              flag is portability: MAP_STACK exists (and  has  an  effect)  on
239              some other systems (e.g., some of the BSDs).
240
241       MAP_SYNC (since Linux 4.15)
242              This flag is available only with the MAP_SHARED_VALIDATE mapping
243              type; mappings of type  MAP_SHARED  will  silently  ignore  this
244              flag.  This flag is supported only for files supporting DAX (di‐
245              rect mapping of persistent memory).  For other files, creating a
246              mapping with this flag results in an EOPNOTSUPP error.
247
248              Shared  file  mappings with this flag provide the guarantee that
249              while some memory is mapped writable in the address space of the
250              process,  it will be visible in the same file at the same offset
251              even after the system crashes or is  rebooted.   In  conjunction
252              with  the  use  of  appropriate  CPU instructions, this provides
253              users of such mappings with a more efficient way of making  data
254              modifications persistent.
255
256       MAP_UNINITIALIZED (since Linux 2.6.33)
257              Don't  clear  anonymous pages.  This flag is intended to improve
258              performance on embedded devices.  This flag is honored  only  if
259              the  kernel was configured with the CONFIG_MMAP_ALLOW_UNINITIAL‐
260              IZED option.  Because of the security implications, that  option
261              is  normally  enabled  only  on  embedded devices (i.e., devices
262              where one has complete control of the contents of user memory).
263
264       Of the above flags, only MAP_FIXED is  specified  in  POSIX.1-2001  and
265       POSIX.1-2008.  However, most systems also support MAP_ANONYMOUS (or its
266       synonym MAP_ANON).
267
268   munmap()
269       The munmap() system call deletes the mappings for the specified address
270       range,  and  causes further references to addresses within the range to
271       generate invalid memory references.  The region is  also  automatically
272       unmapped  when  the  process is terminated.  On the other hand, closing
273       the file descriptor does not unmap the region.
274
275       The address addr must be a multiple of the page size (but  length  need
276       not  be).   All  pages containing a part of the indicated range are un‐
277       mapped, and subsequent references to these pages will generate SIGSEGV.
278       It  is  not an error if the indicated range does not contain any mapped
279       pages.
280

RETURN VALUE

282       On success, mmap() returns a pointer to the mapped area.  On error, the
283       value  MAP_FAILED  (that is, (void *) -1) is returned, and errno is set
284       to indicate the error.
285
286       On success, munmap() returns 0.  On failure, it returns -1,  and  errno
287       is set to indicate the error (probably to EINVAL).
288

ERRORS

290       EACCES A  file descriptor refers to a non-regular file.  Or a file map‐
291              ping was  requested,  but  fd  is  not  open  for  reading.   Or
292              MAP_SHARED  was  requested  and PROT_WRITE is set, but fd is not
293              open in read/write (O_RDWR) mode.  Or PROT_WRITE is set, but the
294              file is append-only.
295
296       EAGAIN The  file  has  been  locked, or too much memory has been locked
297              (see setrlimit(2)).
298
299       EBADF  fd is not a valid file descriptor  (and  MAP_ANONYMOUS  was  not
300              set).
301
302       EEXIST MAP_FIXED_NOREPLACE  was  specified in flags, and the range cov‐
303              ered by addr and length clashes with an existing mapping.
304
305       EINVAL We don't like addr, length, or offset (e.g., they are too large,
306              or not aligned on a page boundary).
307
308       EINVAL (since Linux 2.6.12) length was 0.
309
310       EINVAL flags    contained   none   of   MAP_PRIVATE,   MAP_SHARED,   or
311              MAP_SHARED_VALIDATE.
312
313       ENFILE The system-wide limit on the total number of open files has been
314              reached.
315
316       ENODEV The underlying filesystem of the specified file does not support
317              memory mapping.
318
319       ENOMEM No memory is available.
320
321       ENOMEM The process's maximum number of mappings  would  have  been  ex‐
322              ceeded.   This error can also occur for munmap(), when unmapping
323              a region in the middle of an existing mapping,  since  this  re‐
324              sults in two smaller mappings on either side of the region being
325              unmapped.
326
327       ENOMEM (since Linux 4.7) The process's RLIMIT_DATA limit, described  in
328              getrlimit(2), would have been exceeded.
329
330       EOVERFLOW
331              On  32-bit  architecture  together with the large file extension
332              (i.e., using 64-bit off_t): the number of pages used for  length
333              plus  number  of  pages  used for offset would overflow unsigned
334              long (32 bits).
335
336       EPERM  The prot argument asks for PROT_EXEC but the mapped area belongs
337              to a file on a filesystem that was mounted no-exec.
338
339       EPERM  The operation was prevented by a file seal; see fcntl(2).
340
341       EPERM  The MAP_HUGETLB flag was specified, but the caller was not priv‐
342              ileged (did not have the CAP_IPC_LOCK capability) and is  not  a
343              member  of  the sysctl_hugetlb_shm_group group; see the descrip‐
344              tion of /proc/sys/vm/sysctl_hugetlb_shm_group in
345
346       ETXTBSY
347              MAP_DENYWRITE was set but the object specified by fd is open for
348              writing.
349
350       Use of a mapped region can result in these signals:
351
352       SIGSEGV
353              Attempted write into a region mapped as read-only.
354
355       SIGBUS Attempted  access  to  a page of the buffer that lies beyond the
356              end of the mapped file.  For an explanation of the treatment  of
357              the  bytes  in  the page that corresponds to the end of a mapped
358              file that is not a multiple of the page size, see NOTES.
359

ATTRIBUTES

361       For an  explanation  of  the  terms  used  in  this  section,  see  at‐
362       tributes(7).
363
364       ┌────────────────────────────────────────────┬───────────────┬─────────┐
365Interface                                   Attribute     Value   
366       ├────────────────────────────────────────────┼───────────────┼─────────┤
367mmap(), munmap()                            │ Thread safety │ MT-Safe │
368       └────────────────────────────────────────────┴───────────────┴─────────┘
369

CONFORMING TO

371       POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.
372
373       On POSIX systems on which mmap(), msync(2), and munmap() are available,
374       _POSIX_MAPPED_FILES is defined in <unistd.h> to a value greater than 0.
375       (See also sysconf(3).)
376

NOTES

378       Memory  mapped by mmap() is preserved across fork(2), with the same at‐
379       tributes.
380
381       A file is mapped in multiples of the page size.  For a file that is not
382       a multiple of the page size, the remaining bytes in the partial page at
383       the end of the mapping are zeroed when  mapped,  and  modifications  to
384       that  region  are  not written out to the file.  The effect of changing
385       the size of the underlying file of a mapping on the pages  that  corre‐
386       spond to added or removed regions of the file is unspecified.
387
388       On   some  hardware  architectures  (e.g.,  i386),  PROT_WRITE  implies
389       PROT_READ.  It is  architecture  dependent  whether  PROT_READ  implies
390       PROT_EXEC  or  not.   Portable  programs should always set PROT_EXEC if
391       they intend to execute code in the new mapping.
392
393       The portable way to create a mapping is to specify addr  as  0  (NULL),
394       and  omit  MAP_FIXED  from flags.  In this case, the system chooses the
395       address for the mapping; the address is chosen so as  not  to  conflict
396       with any existing mapping, and will not be 0.  If the MAP_FIXED flag is
397       specified, and addr is 0 (NULL), then the  mapped  address  will  be  0
398       (NULL).
399
400       Certain  flags  constants  are  defined  only  if suitable feature test
401       macros are defined (possibly by default):  _DEFAULT_SOURCE  with  glibc
402       2.19  or later; or _BSD_SOURCE or _SVID_SOURCE in glibc 2.19 and earli‐
403       er.  (Employing _GNU_SOURCE also suffices,  and  requiring  that  macro
404       specifically  would  have  been more logical, since these flags are all
405       Linux-specific.)  The relevant flags are: MAP_32BIT, MAP_ANONYMOUS (and
406       the   synonym   MAP_ANON),   MAP_DENYWRITE,  MAP_EXECUTABLE,  MAP_FILE,
407       MAP_GROWSDOWN, MAP_HUGETLB,  MAP_LOCKED,  MAP_NONBLOCK,  MAP_NORESERVE,
408       MAP_POPULATE, and MAP_STACK.
409
410       An  application  can  determine  which pages of a mapping are currently
411       resident in the buffer/page cache using mincore(2).
412
413   Using MAP_FIXED safely
414       The only safe use for MAP_FIXED is where the address range specified by
415       addr  and  length was previously reserved using another mapping; other‐
416       wise, the use of MAP_FIXED is hazardous  because  it  forcibly  removes
417       preexisting  mappings,  making  it  easy for a multithreaded process to
418       corrupt its own address space.
419
420       For example, suppose that thread A looks  through  /proc/<pid>/maps  in
421       order  to  locate  an  unused  address  range  that  it  can  map using
422       MAP_FIXED, while thread B simultaneously acquires part or all  of  that
423       same    address    range.    When   thread   A   subsequently   employs
424       mmap(MAP_FIXED), it will effectively clobber the mapping that thread  B
425       created.   In this scenario, thread B need not create a mapping direct‐
426       ly; simply making a library call that, internally,  uses  dlopen(3)  to
427       load  some other shared library, will suffice.  The dlopen(3) call will
428       map the library into the process's address space.  Furthermore,  almost
429       any  library call may be implemented in a way that adds memory mappings
430       to the address space, either with this technique, or by simply allocat‐
431       ing memory.  Examples include brk(2), malloc(3), pthread_create(3), and
432       the PAM libraries ⟨http://www.linux-pam.org⟩.
433
434       Since Linux 4.17, a multithreaded program can use  the  MAP_FIXED_NORE‐
435       PLACE  flag to avoid the hazard described above when attempting to cre‐
436       ate a mapping at a fixed address that has not been reserved by a preex‐
437       isting mapping.
438
439   Timestamps changes for file-backed mappings
440       For file-backed mappings, the st_atime field for the mapped file may be
441       updated at any time between the mmap() and the corresponding unmapping;
442       the  first  reference  to a mapped page will update the field if it has
443       not been already.
444
445       The st_ctime and st_mtime field for a file mapped with  PROT_WRITE  and
446       MAP_SHARED  will be updated after a write to the mapped region, and be‐
447       fore a subsequent msync(2) with the MS_SYNC or MS_ASYNC  flag,  if  one
448       occurs.
449
450   Huge page (Huge TLB) mappings
451       For mappings that employ huge pages, the requirements for the arguments
452       of mmap() and munmap() differ somewhat from the requirements  for  map‐
453       pings that use the native system page size.
454
455       For mmap(), offset must be a multiple of the underlying huge page size.
456       The system automatically aligns length to be a multiple of the underly‐
457       ing huge page size.
458
459       For  munmap(), addr, and length must both be a multiple of the underly‐
460       ing huge page size.
461
462   C library/kernel differences
463       This page describes the interface provided by the glibc mmap()  wrapper
464       function.   Originally, this function invoked a system call of the same
465       name.  Since kernel 2.4,  that  system  call  has  been  superseded  by
466       mmap2(2),  and  nowadays  the  glibc  mmap()  wrapper  function invokes
467       mmap2(2) with a suitably adjusted value for offset.
468

BUGS

470       On Linux, there are no guarantees  like  those  suggested  above  under
471       MAP_NORESERVE.   By  default,  any  process can be killed at any moment
472       when the system runs out of memory.
473
474       In kernels before 2.6.7, the MAP_POPULATE flag has effect only if  prot
475       is specified as PROT_NONE.
476
477       SUSv3  specifies  that  mmap() should fail if length is 0.  However, in
478       kernels before 2.6.12, mmap() succeeded in this case:  no  mapping  was
479       created  and the call returned addr.  Since kernel 2.6.12, mmap() fails
480       with the error EINVAL for this case.
481
482       POSIX specifies that the system shall always zero fill any partial page
483       at the end of the object and that system will never write any modifica‐
484       tion of the object beyond its end.  On Linux, when you  write  data  to
485       such  partial  page  after the end of the object, the data stays in the
486       page cache even after the file is closed and unmapped and  even  though
487       the  data  is never written to the file itself, subsequent mappings may
488       see the modified content.  In some cases, this could be fixed by  call‐
489       ing  msync(2)  before the unmap takes place; however, this doesn't work
490       on tmpfs(5) (for example, when using the POSIX shared memory  interface
491       documented in shm_overview(7)).
492

EXAMPLES

494       The  following  program  prints part of the file specified in its first
495       command-line argument to standard output.  The range  of  bytes  to  be
496       printed  is  specified  via  offset and length values in the second and
497       third command-line arguments.  The program creates a memory mapping  of
498       the required pages of the file and then uses write(2) to output the de‐
499       sired bytes.
500
501   Program source
502       #include <sys/mman.h>
503       #include <sys/stat.h>
504       #include <fcntl.h>
505       #include <stdio.h>
506       #include <stdlib.h>
507       #include <unistd.h>
508
509       #define handle_error(msg) \
510           do { perror(msg); exit(EXIT_FAILURE); } while (0)
511
512       int
513       main(int argc, char *argv[])
514       {
515           char *addr;
516           int fd;
517           struct stat sb;
518           off_t offset, pa_offset;
519           size_t length;
520           ssize_t s;
521
522           if (argc < 3 || argc > 4) {
523               fprintf(stderr, "%s file offset [length]\n", argv[0]);
524               exit(EXIT_FAILURE);
525           }
526
527           fd = open(argv[1], O_RDONLY);
528           if (fd == -1)
529               handle_error("open");
530
531           if (fstat(fd, &sb) == -1)           /* To obtain file size */
532               handle_error("fstat");
533
534           offset = atoi(argv[2]);
535           pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
536               /* offset for mmap() must be page aligned */
537
538           if (offset >= sb.st_size) {
539               fprintf(stderr, "offset is past end of file\n");
540               exit(EXIT_FAILURE);
541           }
542
543           if (argc == 4) {
544               length = atoi(argv[3]);
545               if (offset + length > sb.st_size)
546                   length = sb.st_size - offset;
547                       /* Can't display bytes past end of file */
548
549           } else {    /* No length arg ==> display to end of file */
550               length = sb.st_size - offset;
551           }
552
553           addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
554                       MAP_PRIVATE, fd, pa_offset);
555           if (addr == MAP_FAILED)
556               handle_error("mmap");
557
558           s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
559           if (s != length) {
560               if (s == -1)
561                   handle_error("write");
562
563               fprintf(stderr, "partial write");
564               exit(EXIT_FAILURE);
565           }
566
567           munmap(addr, length + offset - pa_offset);
568           close(fd);
569
570           exit(EXIT_SUCCESS);
571       }
572

SEE ALSO

574       ftruncate(2), getpagesize(2),  memfd_create(2),  mincore(2),  mlock(2),
575       mmap2(2),  mprotect(2), mremap(2), msync(2), remap_file_pages(2), setr‐
576       limit(2), shmat(2), userfaultfd(2), shm_open(3), shm_overview(7)
577
578       The descriptions of the following files in  proc(5):  /proc/[pid]/maps,
579       /proc/[pid]/map_files, and /proc/[pid]/smaps.
580
581       B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128–129 and 389–391.
582

COLOPHON

584       This  page  is  part of release 5.12 of the Linux man-pages project.  A
585       description of the project, information about reporting bugs,  and  the
586       latest     version     of     this    page,    can    be    found    at
587       https://www.kernel.org/doc/man-pages/.
588
589
590
591Linux                             2021-03-22                           MMAP(2)
Impressum