#include <stdio.h> /* fprintf */
#include <stdlib.h> /* exit */
#include <string.h> /* memset */
#include <sys/mman.h> /* mmap */
#include <sys/types.h> /* pthread types */
#include <sys/stat.h> /* fchmod */
#include <pthread.h> /* thread primitives */
#include <fcntl.h> /* open */
#include <unistd.h> /* ftruncate */
#include <errno.h> /* errno */
#define LIB_ADDR 0xaabbccdd /* memorable random address */
#define UNMAP_FILE "unmapfile"
#define PAGE_SIZE 1024
#define DIE(msg) \
printf("-----\nDIE:%s\n-----\n", msg)
int
main(int argc, char **argv)
{
int err;
int unmap_fd;
unmap_fd = open(UNMAP_FILE, O_RDWR | O_CREAT);
if (unmap_fd < 0) DIE("open of unmap file failed");
err = ftruncate(unmap_fd, PAGE_SIZE);
if (err) DIE("ftruncate unmap file to page size failed");
err = mmap((void *)LIB_ADDR + PAGE_SIZE, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, unmap_fd, 0);
if (err = MAP_FAILED) DIE("mmap of to-be-unmapped page failed");
return 0;
}
我正在做的很简单。我只想将mmap
文件放到固定地址上,但我收到错误mmap of to-be-unmapped page failed
。我检查了一切,但仍然不知道。
答案 0 :(得分:2)
这个
if (err = MAP_FAILED) DIE("mmap of to-be-unmapped page failed");
应该是
if (err == MAP_FAILED) DIE("mmap of to-be-unmapped page failed");
//Notice the ==
你只是在这里分配,它使条件成立。
mmap(2)
返回void*
。所以err
的类型也是错误的。声明一个新的void指针并使用它:
void *mptr;
....
....
mptr = mmap((void *)LIB_ADDR + PAGE_SIZE, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, unmap_fd, 0);
if (mptr == MAP_FAILED) DIE("mmap of to-be-unmapped page failed");