3

我尝试使用 XCode 4.6 在 MacOSX 10.8.2 下运行 mmap 的简单测试。这个程序如下,映射读取的文件是可以的,而写入指针“target”的访问会导致程序崩溃。错误消息是“EXC_BAD_ACCESS”。

有没有人和我一样的情况?非常感谢。

#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char * argv[]) {
int input, output;
size_t size;

char *source, *target;

input = open("SEK2.txt", O_RDONLY);
if (input == -1) {
    printf("Open source file failed");
    return -1;
}
output = open("test.txt", O_RDWR|O_CREAT|O_TRUNC);
if (output == -1) {
    printf("Open Output file failed");
    return -1;
}

size = lseek(input, 0, SEEK_END);
printf("File size = %d\n", size);

source = (char*)mmap(0, size, PROT_READ, MAP_PRIVATE, input, 0);
if ( source == (void*)-1) {
    printf("Source MMap Error\n");
    return -1;
}

target = (char*)mmap(0, size, PROT_EXEC, MAP_PRIVATE, output, 0);
if ( target == (void*)-1 ) {
    printf( "Target MMap Error\n");
    return -1;
}

memcpy(target, source, size); // EXC_BAD_ACCESS to "target"
munmap(source, size);
munmap(target, size);

close(input);
close(output);

printf("Successed");
return 0;

}

4

3 回答 3

3

我认为您需要ftruncate(output, size);使输出文件足够大。我不相信内核会自动增长文件以容纳写入映射地址的数据。

于 2013-04-27T18:38:39.543 回答
2

您不能仅使用 PROT_EXEC 写入内存映射。你需要 PROT_READ|PROT_WRITE,我不明白你为什么需要 PROT_EXEC。

于 2013-04-27T17:05:10.163 回答
0

mac下不能使用PROT_EXEC,所以不能使用命名的pthread mutex、cond等。

仅使用PROT_READ | PROT_WRITE标志

于 2018-10-24T17:21:53.813 回答