[공부중] mmap 예제

c or linux 2011. 4. 21. 16:54


개념


#include <sys/mman.h>

#define FND_SIZE (0x1000)
#define FND_PHYS_ADDR (0x14000000)   // physical 주소

void fnd_write(int val) 
{
*((unsigned char *)fnd_addr) = fnd_val[val];
*((unsigned char *)fnd_addr+1) = fnd_val[val];
printf("FND_Write : %d done!!\n", val);
}


...
fd = open("/dev/mem", O_RDWR|O_SYNC);
fnd_addr = mmap((void *)0,FND_SIZE,PROT_WRITE|PROT_READ,MAP_SHARED,fd,FND_PHYS_ADDR);
printf("FND I/O Address : %p\n", fnd_addr);
fnd_write(val);
munmap(fnd_addr, FND_SIZE);
close(fd);

...



(void *)0 : 가상주소는 알아서 해줘.
fnd_addr: 가상주소

코드

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <fcntl.h>


#include <sys/mman.h>


#define FND_PHYS_ADDR0 (0x14000000) 

#define FND_PHYS_ADDR1 (0x14100000) 

#define FND_PHYS_ADDR2 (0x14200000) 

#define FND_PHYS_ADDR3 (0x14300000) 


#define FND_SIZE (0x1000)


//#define FND (*((volatile unsigned short *)0xF1000000)) 


void * fnd_addr;


static char fnd_val[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7c,0x27,0x7f,0x67};


void fnd_write(int val) 

{

*((unsigned char *)fnd_addr) = fnd_val[val];

*((unsigned char *)fnd_addr+1) = fnd_val[val];

printf("FND_Write(%d) done!!\n", val);

}


int main(void)

{

    int retn;

    int fd;


    int flag = 0;

    int type;

int val=0;

int i;

off_t addr[] = {FND_PHYS_ADDR0, FND_PHYS_ADDR1,

FND_PHYS_ADDR2, FND_PHYS_ADDR3};

off_t FND_PHYS_ADDR;

    

    while(1)

    {

        printf("\n\n===== FND Test Program ====\n");

        printf(" 0. FND0 Test\n");

        printf(" 1. FND1 Test\n");

        printf(" 2. FND2 Test\n");

        printf(" 3. FND3 Test\n");

        printf(" 4. Program Quit\n");

        do {

            printf(" Select Menu => ");

            scanf("%d", &type);

        } while(type<0 || type>4);

        if(type == 4) break;


        while(1)

        {

            printf("\nFND_%02d Test...\n", type-1);

            do {

                printf("Select FND Write Value(0~9,10.Quit) => ");

                scanf("%d", &val);

            } while(val<0 || val>10);

            if(val == 10) break;


            //fd = open("/dev/FND", O_RDWR);

            fd = open("/dev/mem", O_RDWR|O_SYNC);

            if (fd<0) {

                perror("/dev/mem");

                exit(-1);

            }

            else printf("/dev/mem detected(fd:%d)...\n", fd);


FND_PHYS_ADDR = (off_t)addr[type];

fnd_addr = mmap((void *)0,

FND_SIZE,

PROT_WRITE|PROT_READ,

MAP_SHARED,

fd,

FND_PHYS_ADDR);

if(fnd_addr == NULL) {

                perror("mmap fail!!");

exit(-2);

}

printf("FND I/O Address : %p\n", fnd_addr);

    

            fnd_write(val);

munmap(fnd_addr, FND_SIZE);


            close(fd);

        }

    }

    

    return 0;

}





Posted by '김용환'
,