新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 采用mmap實(shí)現(xiàn)文件的復(fù)制

采用mmap實(shí)現(xiàn)文件的復(fù)制

作者: 時(shí)間:2016-12-01 來源:網(wǎng)絡(luò) 收藏
#include

#include
#include
#include
#include
#include
#include
#include
#include

本文引用地址:http://butianyuan.cn/article/201612/324548.htm

int main(int argc,char *argv[])
{
/*參數(shù)檢測*/
if(argc < 2)
{
printf("Error!!");
exit(-1);
}
/*打開文件,采用系統(tǒng)函數(shù)*/
int fd =open("/home/gong/program/cprogram/signal12.c",O_RDONLY);
/*采用mmap實(shí)現(xiàn)普通文件到進(jìn)程虛擬存儲(chǔ)器的關(guān)聯(lián)*/
/*也就是將大小隨意的文件以寫時(shí)拷貝頁的方式實(shí)現(xiàn)文件到進(jìn)程虛擬存儲(chǔ)器的映射*/
char * p = (char *)mmap(NULL,atoi(argv[argc-1]),PROT_READ,MAP_PRIVATE,fd,0);
/*將存儲(chǔ)器中的數(shù)據(jù)打印到標(biāo)準(zhǔn)輸出流中*/
fprintf(stdout,p);

/*關(guān)閉文件描述符*/
close(fd);
exit(0);
}

編譯調(diào)試:
[gong@Gong-Computer cprogram]$ gcc -g mmapTest.c -o mmapTest
[gong@Gong-Computer cprogram]$ ./mmapTest 4096
#include
#include
#include
#include
#include
#include
#include

#define MAXBUF2048
void hander1(int sig)
{
pid_t pid;
while((pid = waitpid(-1,NULL,0))>0)
{
printf("Hander reaped child 1",(int)getpid());
}
if(errno != ECHILD)
{
printf("Error!!");
exit(-1);
}
sleep(2);
return ;
}
int main()
{
int i,n;
char buf[MAXBUF];
if(signal(SIGCHLD,hander1)==SIG_ERR)
{
printf("error!!");
exit(-1);
}
for(i = 0; i< 3; i++)
{
if(fork() == 0)/*子進(jìn)程*/
{
printf("Hellofromchild 2",(int)getpid());
sleep(1);
exit(0);
}
}
/*父進(jìn)程處理*/
if((n = read(STDIN_FILENO,buf,sizeof(buf)))<0)
{
printf("error!!");
exit(-1);
}
printf("parent processing input");
while(1)
;
exit(0);
}
以上的結(jié)果表明實(shí)現(xiàn)了將普通的文件采用mmap到進(jìn)程的虛擬存儲(chǔ)器的加載。其實(shí)采用dbg即可檢測是否映射成功,但是采用stdout可以更加的直觀。



關(guān)鍵詞: mmap虛擬存儲(chǔ)

評論


技術(shù)專區(qū)

關(guān)閉