Memory mapped I/O
- Allows an application to map a file into memory
- Programmers can access the file directly through memory
- 어떤 file들을 메모리 공간에 mapping시켜서 pointer들으로 접근할 수 있게 해준다.
mmap
- void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset)
- Maps len bytes of the object represented by the file descriptor fd, starting at offset, into memory
- addr
- Offers a suggestion to the kernel of where best to map the file
- Usually pass 0, 0은 OS에게 memory상의 주소 할당을 맡긴다는 의미이다.
- Returns the actual address in memory where the mapping begins
- prot
- Desired memory protection of the mapping
- Bitwise OR of one or more of the following flags
- PROT_READ
- PROT_WRITE
- PROT_EXEC
- Must not conflict with the open mode of the file
- 원래 file의 권한과 충돌하지 않는한, memory에 mapping된 file의 접근 권한을 설정한다.
- flags
- Bitwise OF of one or more of the following flags
- MAP_FIXED: treat addr as a requirement, not a hint → 정확히 addr위치에 mapping시키고, 이가 불가능하다면 error
- MAP_PRIVATE: mapping is not shared → 다른 process들은 이 file을 memory상에 mapping시킬 수 없다. 그렇기 때문에 file에 바로바로 써주지 않는다.
- MAP_SHARED: shares the mapping with all other processes that map this same file (i.e., writing into the mapping is equivalent to writing to the file) → 공유가능, file들의 data도 실시간으로 공유할 수 있다. OS가 control, 실시간성을 위해 file에 바로바로 써준다.
- Either MAP_SHARED or MAP_PRIVATE must be specified, but not both
- Bitwise OF of one or more of the following flags
- offset
- Both the addr and offset parameters nust be aligned on a page-sized boundary
- Integer multiples of the page size
- int page_size = getpagesize();
- int page_size = PAGE_SIZE;
- page는 OS가 memory를 관리하기 위한 조각의 단위이다. 그래서 OS가 관리하기 위해서는 file의 사이즈가 page size의 배수, 즉 page size단위가 되어야한다. 일반적으로 page size는 4KB이지만, capability를 위해서 page size를 받아주는 것을 추천
- Both the addr and offset parameters nust be aligned on a page-sized boundary
- Return value
- On success, location of the mapping
- On failure, MAP_FAILED
munmap
- int munmap(void *addr, size_t len)
- Removes any mappings that contain pages located anywhere in the process address space starting at addr, and continuing for len bytes
- addr에서 시작해서 len바이트만큼의 mapping된 file을 unmapping시키는 system call이다.
- Return value
- On success, 0
- On failure, -1
Reference Count
When you map a file decriptor, the file's reference count is incremented
- You can close the file descriptor after mapping the file (still have access to it)
- Decrement of the file's reference count
- munmap()
- Process termination
Example
int main(int argc, char *argv[])
{
struct stat sb;
off_t len;
char *p;
int fd;
if(argc < 2){
printf("usage: %s <file>\n", argv[0]);
return 1;
}
fd = open(argv[1], O_RDONLY);
if(fd == -1){
perror("open");
return 1;
}
if(fstat(fd, &sb) == -1){
perror("fstat");
return 1;
}
if(!S_ISREG(sb.st_mode)){
printf("%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)P
perror("mmap");
return 1;
}
// close해도 mmap하면서 reference count++ 되었기 때문에 file이 아에 닫히지는 않는다
if(close(fd) == -1){
perror("close");
return 1;
}
for(len=0; len<sb.st_size; len++)
putchar(p[len]);
if(munmap(p, sb_st_size) == -1){
perror("munmap");
return 1;
}
return 0;
}
+ fstat()은 주어진 file에 대한 정보들을 return하는 함수이다.
+ S_ISREG()은 주어진 file이 regular file인지 검사하는 함수이다.
Advantages of mmap
- Low overheads
- Reading from and writing to a mmapped file avoids the extraneout copy that occurs when using the read() or write()
- Reading from and writing to a mmapped file does not incut any system call or context switch overhead
- memory mapping을 시키지 않고 file의 data를 읽으려면 open() → read() → buffer → putchar() 를 해야하는데, memory mapping을 하면 pointer로 간단하게 접근할 수 있다는 점이 유리하다.
- Easy to share
- When multiple processes map the same object into memory, the data is shared among all the processes
- 여러 개의 프로세스가 같은 파일을 메모리 공간에 mapping한다면 데이터가 공유될 수 있다는 점이 유리하다.
- Easy to seek
- Seeking around the mapping involves trival pointer manipulations
- No need for lseek()
- Seeking around the mapping involves trival pointer manipulations
Disadvantages of mmap
- Waste of space
- Memory mappings are always an integer number of pages in size
- Difference between the size of the backing file and an integer number of pages is wasted
- page size의 배수와 file size의 간극이 클 수록 버려지는 메모리 공간이 커진다.
- Memory mappings are always an integer number of pages in size
- Limited mapping size
- The memory mappings must fit into the process' address space
- 하지만 64bits 체계에서는 단점이 뚜렷하지 않다.
- High overheads
- Overhead in creating and maintaining the memory mappings and associated data structures inside the kernel
- 파일을 memory에 mapping시킴으로서 그 memory를 관리하는 자료구조들에 의한 overhead가 발생할 수 있다.
- 하지만 advantage에 해당하는 overhead의 감소가 더 크기때문에, mmap을 사용한다.
'[학교 수업] > [학교 수업] 시스템 프로그래밍' 카테고리의 다른 글
[시스템 프로그래밍] Standard I/O Library (1) | 2024.11.28 |
---|---|
[시스템 프로그래밍] I/O Redirection (1) | 2024.11.28 |
[시스템 프로그래밍] Multiplexed I/O (0) | 2024.11.24 |
[시스템 프로그래밍] File Offset (0) | 2024.11.14 |
[시스템 프로그래밍] File I/O (0) | 2024.11.13 |