tonykang22 / study

0 stars 0 forks source link

[리눅스 개발환경] 09. 메모리 매핑 I/O #80

Open tonykang22 opened 2 years ago

tonykang22 commented 2 years ago

09. 메모리 매핑 I/O

메모리 매핑 I/O 개요


mmap 장점


mmap 주의점



mmap

#include <sys/mman.h>

void * mmap (void *addr, size_t len, int prot, int flags, int fd, off_t offset);


참고 사항


예시

void *p;

p = mmap(0, len, PROT_READ, MAP_SHARED, fd, 0); 
if (p == MAP_FAILED)
    perror(“mmap error: “);


errno


munmap

#include <sys/mman.h>

int munmap (void *addr, size_t len);


if (munmap(addr, len) == -1) 
    perror(“munmap error: “);



mremap

#define _GNU_SOURCE

#include <sys/mman.h>

void * mremap(void *addr, size_t old_size, size_t new_size, unsigned long flags);



msync

#include <sys/mman.h>

int msync (void *addr, size_t len, int flags);


if (msync(addr, len, MS_ASYNC) == -1) 
    perror(“msync error: “);



페이징 개요

#include <unistd.h>

long sysconf(int name);



실습

int main(int argc, char *argv[]) {

int fd;
struct stat sb; 
off_t len; 
char *p;

if (argc < 2) {
    printf("Usage: %s <file>\n", argv[0]);
    return -1; 
}

fd = open(argv[1], O_RDONLY); 
if (fd == -1) {
    perror("open error: ");
    return -1; 
}

if (fstat(fd, &sb) == -1) { 
    perror("fstat error: ");
    return -1; 
}

if (!S_ISREG(sb.st_mode)) {
    printf("file %s is not a file\n", argv[1]);
    return 1; 
}

p = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); 
if (p == MAP_FAILED) {
    perror("mmap error: ");
    return -1; 
}

if (close(fd) == -1) { 
    perror("close error: ");
    return -1; 
}

for (len = 0; len < sb.st_size; len++) {
    putchar(p[len]); 
}

if (munmap(p, sb.st_size) == -1) { 
    perror("munmap error: ");
    return -1; 
}

return 0; 

}



- 결과 
<img width="500" alt="image" src="https://user-images.githubusercontent.com/86760744/180645150-ee4335dd-e348-41ea-b919-3ddcfdb8835e.png">