미소를뿌리는감자의 코딩
[web server] Dealing with static contents 본문
728x90
1. 개요
Computer Systems A Programmer's Perspective에서 페이지 930의 11.9 문제를 풀어보았다.
[11.9]
TINY를 수정해서 정적 컨텐츠를 처리할 때 요청한 파일을 mmap과 rio_readn 대신에 malloc, rio_readn, rio_writen을 사용해서 연결 식별자에게 복사하도록 하시오.
void serve_static(int fd, char *filename, int filesize)
{
int srcfd;
char *srcp, filetype[MAXLINE], buf[MAXBUF];
/* Send response headers to client */
get_filetype(filename, filetype);
sprintf(buf, "HTTP/1.0 200 OK\r\n");
sprintf(buf, "%sServer: Tiny Web Server\r\n", buf);
sprintf(buf, "%sConnection: close\r\n", buf);
sprintf(buf, "%sContent-length: %d\r\n", buf, filesize);
sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, filetype);
Rio_writen(fd, buf, strlen(buf));
printf("Response headers:\n");
printf("%s", buf);
/* Send response body to client */
srcfd = Open(filename, O_RDONLY, 0);
srcp = Mmap(0, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0);
Close(srcfd);
Rio_writen(fd, srcp, filesize);
Munmap(srcp, filesize);
}
코드 중 /* Send response body to client */ 밑을 중점으로 볼 것이다.
srcfd로 파일을 열고 식별자를 가지고 온다. 해당 식별자를 이용해서, 가상 메모리 영역으로 매핑한 것을 srcp라고 한다.
매핑 된 후에는, srcfd가 필요 없으므로 Close를 해주고, srcp를 client에게 넘겨준다. 이후 가상 메모리를 Mummap으로 해제 해 준다.
다음으로는, 위 문제를 적용시킨 코드이다.
void serve_static(int fd, char *filename, int filesize)
{
int srcfd;
char *srcp, filetype[MAXLINE], buf[MAXBUF];
/* Send response headers to client */
get_filetype(filename, filetype);
sprintf(buf, "HTTP/1.0 200 OK\r\n");
sprintf(buf, "%sServer: Tiny Web Server\r\n", buf);
sprintf(buf, "%sConnection: close\r\n", buf);
sprintf(buf, "%sContent-length: %d\r\n", buf, filesize);
sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, filetype);
Rio_writen(fd, buf, strlen(buf));
printf("Response headers:\n");
printf("%s", buf);
/* Send response body to client */
srcfd = Open(filename, O_RDONLY, 0);
srcp = (char *)malloc(filesize);
if (srcp == NULL) {
Close(srcfd);
clienterror(fd, filename, "500", "Internal Server Error", "Memory allocation failed");
return;
}
if (rio_readn(srcfd, srcp, filesize) != filesize) {
Close(srcfd);
free(srcp);
clienterror(fd, filename, "500", "Internal Server Error", "Memory allocation failed");
return;
}
Close(srcfd);
Rio_writen(fd, srcp, filesize);
free(srcp);
}
Mmap 대신에 malloc을 이용해서 srcp에 rio_readn을 해주었고, Rio_writen을 해주었다.
Mmap은 파일을 메모리에 매핑하는 것이고 Malloc은 힙 영역에 메모리 블록을 할당하는 것이다.
파일을 메모리에 매핑하는 것은 파일과 직접 연결을 할 수 있도록 하여 더 빠르게 처리될 수 있다.
728x90
'코딩 이야기' 카테고리의 다른 글
[Web Server] Proxy code (2) | 2024.10.28 |
---|---|
[RB Tree] 삭제 (1) | 2024.10.13 |
LCS ( Longest common substring, Longest Common subsequence) (0) | 2024.09.28 |
Knap Sack (2) | 2024.09.27 |
[~ to Many] Dijkstra Algorithm & Floyd Warshall Algorithm (2) | 2024.09.21 |