1mmap(2)                       System Calls Manual                      mmap(2)
2
3
4

NAME

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

LIBRARY

9       Standard C library (libc, -lc)
10

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

ATTRIBUTES

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

VERSIONS

376       On   some  hardware  architectures  (e.g.,  i386),  PROT_WRITE  implies
377       PROT_READ.  It is  architecture  dependent  whether  PROT_READ  implies
378       PROT_EXEC  or  not.   Portable  programs should always set PROT_EXEC if
379       they intend to execute code in the new mapping.
380
381       The portable way to create a mapping is to specify addr  as  0  (NULL),
382       and  omit  MAP_FIXED  from flags.  In this case, the system chooses the
383       address for the mapping; the address is chosen so as  not  to  conflict
384       with any existing mapping, and will not be 0.  If the MAP_FIXED flag is
385       specified, and addr is 0 (NULL), then the  mapped  address  will  be  0
386       (NULL).
387
388       Certain  flags  constants  are  defined  only  if suitable feature test
389       macros are defined (possibly by default):  _DEFAULT_SOURCE  with  glibc
390       2.19  or  later;  or  _BSD_SOURCE  or  _SVID_SOURCE  in  glibc 2.19 and
391       earlier.  (Employing _GNU_SOURCE  also  suffices,  and  requiring  that
392       macro  specifically would have been more logical, since these flags are
393       all Linux-specific.)  The relevant flags are: MAP_32BIT,  MAP_ANONYMOUS
394       (and  the  synonym  MAP_ANON), MAP_DENYWRITE, MAP_EXECUTABLE, MAP_FILE,
395       MAP_GROWSDOWN, MAP_HUGETLB,  MAP_LOCKED,  MAP_NONBLOCK,  MAP_NORESERVE,
396       MAP_POPULATE, and MAP_STACK.
397
398   C library/kernel differences
399       This  page describes the interface provided by the glibc mmap() wrapper
400       function.  Originally, this function invoked a system call of the  same
401       name.   Since  Linux  2.4,  that  system  call  has  been superseded by
402       mmap2(2), and  nowadays  the  glibc  mmap()  wrapper  function  invokes
403       mmap2(2) with a suitably adjusted value for offset.
404

STANDARDS

406       POSIX.1-2008.
407

HISTORY

409       POSIX.1-2001, SVr4, 4.4BSD.
410
411       On POSIX systems on which mmap(), msync(2), and munmap() are available,
412       _POSIX_MAPPED_FILES is defined in <unistd.h> to a value greater than 0.
413       (See also sysconf(3).)
414

NOTES

416       Memory  mapped  by  mmap()  is  preserved across fork(2), with the same
417       attributes.
418
419       A file is mapped in multiples of the page size.  For a file that is not
420       a multiple of the page size, the remaining bytes in the partial page at
421       the end of the mapping are zeroed when  mapped,  and  modifications  to
422       that  region  are  not written out to the file.  The effect of changing
423       the size of the  underlying  file  of  a  mapping  on  the  pages  that
424       correspond to added or removed regions of the file is unspecified.
425
426       An  application  can  determine  which pages of a mapping are currently
427       resident in the buffer/page cache using mincore(2).
428
429   Using MAP_FIXED safely
430       The only safe use for MAP_FIXED is where the address range specified by
431       addr   and  length  was  previously  reserved  using  another  mapping;
432       otherwise, the use  of  MAP_FIXED  is  hazardous  because  it  forcibly
433       removes  preexisting  mappings,  making  it  easy  for  a multithreaded
434       process to corrupt its own address space.
435
436       For example, suppose that thread  A  looks  through  /proc/pid/maps  in
437       order  to  locate  an  unused  address  range  that  it  can  map using
438       MAP_FIXED, while thread B simultaneously acquires part or all  of  that
439       same    address    range.    When   thread   A   subsequently   employs
440       mmap(MAP_FIXED), it will effectively clobber the mapping that thread  B
441       created.   In  this  scenario,  thread  B  need  not  create  a mapping
442       directly; simply making a library call that, internally, uses dlopen(3)
443       to  load  some  other shared library, will suffice.  The dlopen(3) call
444       will map the library into the process's  address  space.   Furthermore,
445       almost  any  library  call may be implemented in a way that adds memory
446       mappings to the address space, either with this technique, or by simply
447       allocating     memory.     Examples    include    brk(2),    malloc(3),
448       pthread_create(3), and the PAM libraries ⟨http://www.linux-pam.org⟩.
449
450       Since Linux 4.17, a multithreaded program can use  the  MAP_FIXED_NORE‐
451       PLACE  flag to avoid the hazard described above when attempting to cre‐
452       ate a mapping at a fixed address that has not been reserved by a preex‐
453       isting mapping.
454
455   Timestamps changes for file-backed mappings
456       For file-backed mappings, the st_atime field for the mapped file may be
457       updated at any time between the mmap() and the corresponding unmapping;
458       the  first  reference  to a mapped page will update the field if it has
459       not been already.
460
461       The st_ctime and st_mtime field for a file mapped with  PROT_WRITE  and
462       MAP_SHARED  will be updated after a write to the mapped region, and be‐
463       fore a subsequent msync(2) with the MS_SYNC or MS_ASYNC  flag,  if  one
464       occurs.
465
466   Huge page (Huge TLB) mappings
467       For mappings that employ huge pages, the requirements for the arguments
468       of mmap() and munmap() differ somewhat from the requirements  for  map‐
469       pings that use the native system page size.
470
471       For mmap(), offset must be a multiple of the underlying huge page size.
472       The system automatically aligns length to be a multiple of the underly‐
473       ing huge page size.
474
475       For  munmap(), addr, and length must both be a multiple of the underly‐
476       ing huge page size.
477

BUGS

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

EXAMPLES

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

SEE ALSO

583       ftruncate(2), getpagesize(2),  memfd_create(2),  mincore(2),  mlock(2),
584       mmap2(2),  mprotect(2), mremap(2), msync(2), remap_file_pages(2), setr‐
585       limit(2), shmat(2), userfaultfd(2), shm_open(3), shm_overview(7)
586
587       The descriptions of the following  files  in  proc(5):  /proc/pid/maps,
588       /proc/pid/map_files, and /proc/pid/smaps.
589
590       B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128–129 and 389–391.
591
592
593
594Linux man-pages 6.05              2023-07-20                           mmap(2)
Impressum