40 lines
929 B
C
40 lines
929 B
C
#include <sys/mman.h>
|
|
#include <sys/types.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
typedef struct {
|
|
char name[4];
|
|
int age;
|
|
} people;
|
|
|
|
int main(int argc, char **argv) {
|
|
int fd, i;
|
|
people *p_map;
|
|
char temp;
|
|
|
|
// Open or create file, and set its length to 5 people
|
|
fd = open(argv[1], O_CREAT|O_RDWR|O_TRUNC, 00777);
|
|
lseek(fd, sizeof(people)*5-1, SEEK_SET);
|
|
write(fd, "", 1);
|
|
|
|
// Set 10 people at the return addr of mmap
|
|
p_map = (people *)mmap(NULL, sizeof(people)*10, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
|
|
close(fd);
|
|
|
|
temp = 'a';
|
|
for (i = 0; i < 10; i++) {
|
|
temp += 1;
|
|
memcpy((*(p_map+i)).name, &temp, 2);
|
|
(*(p_map+i)).age = 20 + i;
|
|
}
|
|
printf("initialize over\n");
|
|
sleep(10); // Sleep 10 seconds to wait other process
|
|
munmap(p_map, sizeof(people)*10);
|
|
printf("umap ok\n");
|
|
return 0;
|
|
}
|
|
|