1: /*
2: author:justinzhang
3: email:uestczhangchao@gmail.com
4: time:2012-8-22 18:50:23:
5: desc: a buggy program from bbs.qshpan.com, i use strerror(errno) to locate
6: the problem, the problem is that i didn't give the second command line arguments.
7: After making it running properly, i add some exception handling code:)
8: */
9: #include<errno.h>
10: #include<sys/mman.h>
11: #include<sys/types.h>
12: #include<fcntl.h>
13: #include<unistd.h>
14: #include<string.h>
15: #include<stdio.h>
16: #include<sys/stat.h>
17: #include<stdlib.h>
18: typedef struct
19: {
20: char name[4];
21: int age;
22: }people;
23: main(int argc,char** argv)
24: {
25: int fd ,i;
26: people *p_map;
27: char temp;
28: if(argc < 2){
29: printf("usage %s filename\n",argv[0]);
30: exit(EXIT_FAILURE);
31: }
32: fd=open(argv[1],O_CREAT|O_RDWR|O_TRUNC,00777);
33: if(fd == -1)
34: {
35: printf("error:%s\n",strerror(errno));
36: exit(EXIT_FAILURE);
37: }
38: lseek(fd,sizeof(people)*5-1,SEEK_SET);
39: write(fd,"",1);
40: p_map=(people*)mmap(NULL,sizeof(people)*10,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
41: close(fd);
42: temp='a';
43: for(i=0;i<10;i++)
44: {
45: temp += 1;
46: printf("%s\n",strerror(errno));
47: memcpy((*(p_map+i)).name,&temp,2);
48: (*(p_map+i)).age=20+i;
49: }
50: printf("initialize over!\n");
51: sleep(10);
52: munmap(p_map,sizeof(people)*10);
53: printf("umap ok!\n");
54: }