#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/stat.h>
int main()
{
int fdin,fdout;
struct stat statbuf;
void *src,*dst;
char *p;
int i,j;
fdin=open("test1",O_RDONLY|O_RDWR);
fdout=open("test2",O_CREAT|O_RDWR|O_TRUNC,S_IRUSR|S_IWUSR);//需設定權限的flag,如果只能寫,會產生SIGSEGV信號

struct stat st;
fstat(fdin,&st);
lseek(fdout,st.st_size-1,SEEK_SET);
write(fdout,"",1); //如果未設置,寫到檔案結尾的時候,會產生SIGBUS的信號


if((src=mmap(0,st.st_size,PROT_READ,MAP_PRIVATE,fdin,0))==MAP_FAILED)
{
printf("src map error\n");
return -1;
}

/*如果使用 MAP_PRIVATE 則檔案不會真正寫入*/
if((dst=mmap(0,st.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fdout,0))==MAP_FAILED)
{
printf("dest map error\n");
return -1;
}

memcpy(dst,&src[60],10);
memcpy(&dst[10],&src[80],10);


msync( dst, st.st_size, MS_ASYNC);
munmap(src, st.st_size);
munmap(dst, st.st_size);
close(fdin); //即使關閉還是可以修改文件的內容
close(fdout);
printf("ok!\n");
return 0;
}

參考網址:

http://checko.blogspot.tw/2005/04/mmap-mmap-file.html

http://welkinchen.pixnet.net/blog/post/41312211-%E8%A8%98%E6%86%B6%E9%AB%94%E6%98%A0%E5%B0%84%E5%87%BD%E6%95%B8-mmap-%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95

http://www.cppblog.com/lmlf001/archive/2007/09/13/32112.html

arrow
arrow
    文章標籤
    MAP_PRIVATE MAP_SHARED mmap
    全站熱搜

    Yisin 發表在 痞客邦 留言(0) 人氣()