在MacOSX 10.8.2下使用XCode 4.6进行写入的mmap会使程序崩溃 [英] mmap for write under MacOSX 10.8.2 with XCode 4.6 will make program crash

查看:57
本文介绍了在MacOSX 10.8.2下使用XCode 4.6进行写入的mmap会使程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用XCode 4.6在MacOSX 10.8.2下运行mmap的简单测试.该程序如下所示,映射为读取的文件是可以的,而对写指针"target"的访问将使程序崩溃. 错误消息是"EXC_BAD_ACCESS".

I try to run a simple test of mmap under MacOSX 10.8.2, with XCode 4.6. This program is as follows, the file mapped for read is OK while the access to the write pointer "target" will make the program crash. Error message is "EXC_BAD_ACCESS".

有人和我有同样的案子吗? 非常感谢.

Does anyone have the same case with me ? Thanks a lot.

#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;

}

推荐答案

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

I think you need to ftruncate(output, size); to make the output file large enough. I don't believe the kernel with automatically grow a file to accommodate data written to the mapped addresses.

这篇关于在MacOSX 10.8.2下使用XCode 4.6进行写入的mmap会使程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆