日期:2014-05-16 浏览次数:20736 次
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
int main(int argc, char **argv)
{
int fd,i;
int flength;
char *p;
char tmp;
if (argc<2) {
printf("please enter a filename\n");
exit(-1);
}
fd=open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
if (fd<0) {
perror("open");
exit(-1);
}
flength=lseek(fd,20,SEEK_SET);
write(fd, " ", 1);
printf("flength=%d\n", flength);
if (flength<0) {
perror("lseek error");
exit(-1);
}
p=(char *)mmap(NULL,flength,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if (p==MAP_FAILED) {
perror("mmap error");
exit(-1);
}
tmp='a';
for (i=0; i<flength-1; i++) {
p[i]=tmp;
tmp+=1;
}
p[i]='\0';
printf("initialize over.......p=%s\n", p);
sleep(10);
munmap(p,flength);
printf("unmap ok\n");
return 0;
}