專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計(jì)實(shí)例 >> 瀏覽文章

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

作者:公平   來(lái)源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間:2014年03月14日   【字體:


#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<sys/mman.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>

int main(int argc,char *argv[])
{
        /*參數(shù)檢測(cè)*/
        if(argc < 2)
        {
                printf("Error!!\n");
                exit(-1);
        }
        /*打開(kāi)文件,采用系統(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í)拷貝頁(yè)的方式實(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<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<signal.h>
#include<errno.h>

#define MAXBUF 2048
void hander1(int sig)
{
pid_t pid;
while((pid = waitpid(-1,NULL,0))>0)

printf("Hander reaped child 1\n",(int)getpid());
}
if(errno != ECHILD)
{
printf("Error!!\n");
exit(-1);
}
sleep(2);
return ;
}
int main()
{
int i,n;
char buf[MAXBUF];
if(signal(SIGCHLD,hander1)==SIG_ERR)

printf("error!!\n");
exit(-1);
}
for(i = 0; i< 3; i++)
{
if(fork() == 0) /*子進(jìn)程*/
{
printf("Hello from child 2\n",(int)getpid());
sleep(1);
exit(0);
}
}
/*父進(jìn)程處理*/
if((n = read(STDIN_FILENO,buf,sizeof(buf)))<0)

printf("error!!\n");
exit(-1);
}
printf("parent processing input\n");
while(1)
;
exit(0);
}
以上的結(jié)果表明實(shí)現(xiàn)了將普通的文件采用mmap到進(jìn)程的虛擬存儲(chǔ)器的加載。其實(shí)采用dbg即可檢測(cè)是否映射成功,但是采用stdout可以更加的直觀。
 

關(guān)閉窗口

相關(guān)文章