gpt4 book ai didi

c - 基本 mmap(2) 调用失败

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:52 25 4
gpt4 key购买 nike

我已经为这段非常基本的代码绞尽脑汁好几个小时了,但我一直没能理解为什么 mmap(2) 会失败。

#include <sys/mman.h>
#include <sys/user.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>

#define NPAGES 50
#define SLABSIZE (PAGE_SIZE * NPAGES) // 200 kB

int
main(int argc, char *argv[])
{
char *slab;

printf("DEBUG: mmap(%#x, %u, %#x, %#x, %d, %u)\n",
NULL, SLABSIZE, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
slab = mmap(NULL, SLABSIZE, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
if (slab == MAP_FAILED)
err(1, "mmap");
}

但是当我运行它时:

$ make mmap
cc mmap.c -o mmap
$ ./mmap
DEBUG: mmap(0, 204800, 0x3, 0x20, -1, 0)
mmap: mmap: Invalid argument

我检查并重新检查了 mmap(2) 的联机帮助页 [1],似乎所有要求都没有问题,但我一定遗漏了一些东西。我正在运行 Linux 内核 4.8.13。

谢谢。——杰瑞米

[1] http://man7.org/linux/man-pages/man2/mmap.2.html

最佳答案

strace 执行您的程序时,我看到:

mmap(NULL, 204800, PROT_READ|PROT_WRITE, MAP_FILE|MAP_ANONYMOUS, -1, 0) = -1 EINVAL (Invalid argument)

您忘记了 MAP_SHARED 标志(或 MAP_PRIVATE 标志)。有了它(MAP_SHAREDMAP_PRIVATE,但您需要其中之一)您的程序可以运行:

    slab = mmap(NULL, SLABSIZE, PROT_READ | PROT_WRITE, 
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);

引用mmap(2)手册页:

This behavior is determined by including exactly one of the following values in flags:

(重点是我的)

  MAP_SHARED
Share this mapping. Updates to the mapping are visible to
other processes mapping the same region, and (in the case of
file-backed mappings) are carried through to the underlying
file. (To precisely control when updates are carried through
to the underlying file requires the use of msync(2).)

MAP_PRIVATE
Create a private copy-on-write mapping. Updates to the
mapping are not visible to other processes mapping the same
file, and are not carried through to the underlying file. It
is unspecified whether changes made to the file after the
mmap() call are visible in the mapped region.

因此,在紧张不安之前的一般建议是:再次阅读文档;小睡一下;再次阅读文档并思考您错过了什么。

另一个提示是使用 strace(1)在某些(或多个)现有 可执行文件上。你会学到很多东西。

关于c - 基本 mmap(2) 调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41334062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com