- 论坛徽章:
- 0
|
mmap使用时报错,invalid argument, 如果把MAP_SHARED 换成 MAP_PRIVATE就可以了,这是为什么?
/* Created by Anjuta version 1.2.4a */
/* This file will not be overwritten */
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main()
{
int fdes;
void* mapaddr = NULL;
struct stat stat;
size_t length = 0;
int pagesize = 0;
int remaining = 0;
fdes = open("./main.c", O_RDWR, 0);
if(fdes < 0){
perror("open file error\n");
return -1;
}
if(fstat(fdes, &stat) < 0){
perror("fstat error\n");
return -1;
}
length = stat.st_size;
pagesize = getpagesize();
remaining = length % pagesize;
if(remaining != 0)
{
length = length + pagesize - remaining;
}
mapaddr = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_PRIVATE, fdes, 0);
if(mapaddr == (void*)(-1)){
if(errno == EINVAL)
fprintf(stderr, "invalid arguments\n");
perror("mmap error");
return -1;
}
if(write(1, mapaddr, stat.st_size) < 0)
{
perror("write error ");
}
return (0);
} |
|