【发布时间】:2015-10-08 09:00:57
【问题描述】:
#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。我已经检查了所有内容,但仍然不知道。
【问题讨论】:
-
err = MAP_FAILED应该是err == MAP_FAILED? -
=用于从右到左赋值。使用==进行比较。if (err == MAP_FAILED) -
专业提示:启用编译器警告(例如
gcc -Wall ...)会立即显示此错误 - 始终在启用警告的情况下编译,不要忽略任何此类警告! -
@Himanshu 感谢您的回复。我已按照建议修改了所有更改,但同样的问题仍然存在。
-
@immibis 感谢您的回复。我已按照建议修改了所有更改,但同样的问题仍然存在。
标签: c mmap invalid-argument