I am trying to run a simple mmap test under MacOSX 10.8.2 with Xcode 4.6. This program looks as follows: the file displayed for reading is in order, and access to the "target" write pointer will cause the program to crash. The error message is "EXC_BAD_ACCESS".
Do I have the same case with me? Many thanks.
#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);
munmap(source, size);
munmap(target, size);
close(input);
close(output);
printf("Successed");
return 0;
}
source
share