H
Hao Xu
Hi everyone!
I found that if you want to write to the memory got by mmap(), you have
to get the file descriptor for mmap() in O_RDWR mode. If you got the
file descriptor in O_WRONLY mode, then writing to the memory got by
mmap() will lead to segmentation fault. Anyone knows why? Is this a rule
or a bug?
What if I just want to write to the file and nothing else?
Please, look at my tiny program, I wrote this to test mmap(), it is cute.
#include <stdio.h>
typedef struct{
char name[4];
int age;
} people;
int main(int argc, char** argv) {
int fd, i;
people *p_map;
char temp;
fd = open(argv[1], O_RDWR|O_TRUNC); //this works fine
//fd = open(argv[1], O_WRONLY|O_TRUNC); this will cause segmentation fault
if (fd == -1) {
perror("open()");
}
lseek(fd, sizeof(people)*5-1, SEEK_SET);
write(fd, " " , 1);
p_map = (people *)mmap(NULL,sizeof(people)*5,PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
memset(p_map, '\0', sizeof(people)*5);
temp = 'b';
for(i=0; i<5; i++) {
temp++;
//(p_map+i)->name = "aaa";
//memcpy((p_map+i)->name, &temp, 2);
memset((p_map+i)->name, temp, 3);
(p_map+i)->age = 20+i;
}
printf("initialize over\n");
for(i=0; i<5; i++) {
printf("%s\t%d\n", (p_map+i)->name, (p_map+i)->age);
}
sleep(10);
munmap(p_map, sizeof(people)*5);
printf( "umap ok\n" );
return 0;
}
I found that if you want to write to the memory got by mmap(), you have
to get the file descriptor for mmap() in O_RDWR mode. If you got the
file descriptor in O_WRONLY mode, then writing to the memory got by
mmap() will lead to segmentation fault. Anyone knows why? Is this a rule
or a bug?
What if I just want to write to the file and nothing else?
Please, look at my tiny program, I wrote this to test mmap(), it is cute.
#include <stdio.h>
typedef struct{
char name[4];
int age;
} people;
int main(int argc, char** argv) {
int fd, i;
people *p_map;
char temp;
fd = open(argv[1], O_RDWR|O_TRUNC); //this works fine
//fd = open(argv[1], O_WRONLY|O_TRUNC); this will cause segmentation fault
if (fd == -1) {
perror("open()");
}
lseek(fd, sizeof(people)*5-1, SEEK_SET);
write(fd, " " , 1);
p_map = (people *)mmap(NULL,sizeof(people)*5,PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
memset(p_map, '\0', sizeof(people)*5);
temp = 'b';
for(i=0; i<5; i++) {
temp++;
//(p_map+i)->name = "aaa";
//memcpy((p_map+i)->name, &temp, 2);
memset((p_map+i)->name, temp, 3);
(p_map+i)->age = 20+i;
}
printf("initialize over\n");
for(i=0; i<5; i++) {
printf("%s\t%d\n", (p_map+i)->name, (p_map+i)->age);
}
sleep(10);
munmap(p_map, sizeof(people)*5);
printf( "umap ok\n" );
return 0;
}