You are on page 1of 5

mmap()#include <unistd.h>#include <sys/mman.

h>

MAP_FAILED(-1)
errno
EBADF fd
EACCES MAP_PRIVATE
MAP_SHARED PROT_WRITE
EINVAL startlength offset
EAGAIN
ENOMEM

mmap()
mmap()

mmap

mmap()

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main(int argc, char **argv)


{
struct stat st;
//
int fd = -1;
if((fd = open("File", O_RDONLY)) == -1)
{
printf("open File error!\n");
return -1;
}

//
if(fstat(fd, &st) == -1)
{
printf("get st error!\n");
return -1;
}

//
void *start = NULL;
if((start = mmap(start, st.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0)) ==
MAP_FAILED)
{
printf("mmap error!\n");
return -1;
}
printf("%s\n", (char *)start);

//
if(munmap(start, st.st_size) == -1)
{
printf("munmap error!\n");
return -1;
}
close(fd);
return 0;
}

fstat(fd, st) 0-1 fd


st st

fstat() stat() stat()

mmap()
mmap()

mmap()
1munmap()

addr mmap()len

0-
1
2msync()


munmap() msync()

addr
len
flags MS_ASYNC/ MS_SYNC/ MS_INVALIDATE


MS_ASYNC
MS_SYNC
MS_INVALIDATE


0-1

3madvise()
mmap()

Linux
4K
2G
madvise() mmap()

madvise()

addr mmap()
len
behav
0-1

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main(int argc, char **argv)


{
struct stat st;

//
int fd = -1;
if((fd = open("File", O_RDONLY)) == -1)
{
printf("open File error!\n");
return -1;
}

//
if(fstat(fd, &st) == -1)
{
printf("get st error!\n");
return -1;
}

//
void *start = NULL;
if((start = mmap(start, st.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0)) ==
MAP_FAILED)
{
printf("mmap error!\n");
return -1;
}

// advise()
if(madvise(start, st.st_size, MADV_WILLNEED | MADV_SEQUENTIAL) == -1)
{
printf("madvise error!\n");
return -1;
}
printf("%s\n", (char *)start);

//
if(munmap(start, st.st_size) == -1)
{
printf("munmap error!\n");
return -1;
}
close(fd);

return 0;
}

mmap() Mayuyu
fmemopen()
mmap() mmap()

You might also like