#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
The basic idea is to map the content of a file to memory.
size_t length: the number of bytes you want to map
off_t offset: the start address of file you want to map. or you could say the offset of the current file you are going to map it to memory.
int fd: the file descriptor you the file.
int prot: memory protection of the memory just mapped.
The prot argument describes the desired memory protection of the map‐
ping (and must not conflict with the open mode of the file). It is
either PROT_NONE or the bitwise OR of one or more of the following
flags:
PROT_EXEC Pages may be executed.
PROT_READ Pages may be read.
PROT_WRITE Pages may be written.
PROT_NONE Pages may not be accessed.
int flags: mapped memory is shared with other process or private.
here is the example of mmap usage, but this is not working:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#define STARTADDR 0x400000
#define ENDADDR 0x620de6
#define SIZE ENDADDR - STARTADDR
int main(int argc, char *argv[])
{
int fd1 = open("/dev/mem", O_RDONLY);
if(fd1 == -1)
{
fprintf(stderr, "open error\n");
exit(1);
}
int fd2 = open("staticMem", O_CREAT | O_RDWR);
if(fd1 == -1)
{
fprintf(stderr, "open error\n");
exit(1);
}
void* my_mem = mmap(0, SIZE, PROT_READ, MAP_SHARED, fd1, STARTADDR);
if(my_mem == MAP_FAILED)
{
fprintf(stderr, "map failed\n");
exit(1);
}
if(write(fd2, my_mem, SIZE)!= SIZE)
{
fprintf(stderr, "write error\n");
exit(1);
}
return 1;
}
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#define STARTADDR 0x400000
#define ENDADDR 0x620de6
#define SIZE ENDADDR - STARTADDR
int main(int argc, char *argv[])
{
int fd1 = open("/dev/mem", O_RDONLY);
if(fd1 == -1)
{
fprintf(stderr, "open error\n");
exit(1);
}
int fd2 = open("staticMem", O_CREAT | O_RDWR);
if(fd1 == -1)
{
fprintf(stderr, "open error\n");
exit(1);
}
void* my_mem = mmap(0, SIZE, PROT_READ, MAP_SHARED, fd1, STARTADDR);
if(my_mem == MAP_FAILED)
{
fprintf(stderr, "map failed\n");
exit(1);
}
if(write(fd2, my_mem, SIZE)!= SIZE)
{
fprintf(stderr, "write error\n");
exit(1);
}
return 1;
}
No comments:
Post a Comment