我嘗試使用XCode 4.6在MacOSX 10.8.2下運行一個簡單的mmap測試。該程序如下,映射爲讀取的文件是OK的,而對寫入指針「target」的訪問會使程序崩潰。 錯誤消息是「EXC_BAD_ACCESS」。使用XCode 4.6在MacOSX 10.8.2下編寫mmap將導致程序崩潰
有沒有人與我有同樣的情況? 非常感謝。
#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;
}
謝謝,我已經嘗試過「PROT_READ | PROT_WRITE」,但結果是一樣的... – user2327236 2013-04-27 17:59:07