gpt4 book ai didi

C 'mmap' 导致段错误。有想法吗?

转载 作者:行者123 更新时间:2023-11-30 18:37:57 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,为学校使用“mmap”读取文件。我在创建 map 时遇到一些困难。具体来说,我遇到了段错误。我不太确定我在这里做错了什么,因此我们将不胜感激一些具体的帮助。谢谢。

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

int main(int argc, char* argv[])
{
printf("Hello world!\n");

FILE* fp;// File pointer
int fd;// File descriptor
size_t size;// Length of the file
char* map;// File mmap

/* Open the file */
fp = fopen("data.txt", "r+");

/* Get the file descriptor */
fd = fileno(fp);
printf("FD: %d\n", fd);

/* Get the size of the file */
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("SIZE: %d\n", size);

/* Map the file with mmap */
map = mmap(NULL, size, PROT_READ, 0, fd, 0);

if (map == MAP_FAILED)
{
printf("MMAP FAILED\n");
} else {
printf("MMAP SUCEEDED\n");
}

/* Do something with the map */
int i;
for (i = 0; i < size; i++)
{
char c;
c = map[i];
putchar(c);
}

fclose(fp);

return(0);
}

最佳答案

您没有指定任何内容作为标志参数,您必须按指定的 here 指定 MAP_PRIVATEMAP_SHARED :

The flags argument determines whether updates to the mapping are visible to other processes mapping the same region, and whether updates are carried through to the underlying file. 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 that map this file, and 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.

就您而言,由于您只是读取文件,MAP_PRIVATE 应该足够了。

尝试:

map = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);

关于C 'mmap' 导致段错误。有想法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35375775/

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