mmap for write under MacOSX 10.8.2 with XCode 4.6 will make program crash

偶尔善良 提交于 2019-12-10 18:04:40

问题


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;

}


回答1:


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.




回答2:


You can't write to a memory map with only PROT_EXEC. You need PROT_READ|PROT_WRITE, and I don't see why you want PROT_EXEC at all.




回答3:


Under mac, you cannot use PROT_EXEC, so you cannot use named pthread mutex, cond or etc.

use only PROT_READ | PROT_WRITE flag



来源:https://stackoverflow.com/questions/16254743/mmap-for-write-under-macosx-10-8-2-with-xcode-4-6-will-make-program-crash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!