1 / 37

Nonblocking I/O

Nonblocking I/O. June-Hyun, Moon Computer Communications LAB., Kwangwoon University imp@kw.ac.kr. Introduction. Blocking This means that when we issue a socket call that can not be completed immediately, our process is put to sleep, waiting for the condition be true.

stesha
Télécharger la présentation

Nonblocking I/O

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Nonblocking I/O June-Hyun, Moon Computer Communications LAB., Kwangwoon University imp@kw.ac.kr

  2. Introduction • Blocking • This means that when we issue a socket call that can not be completed immediately, our process is put to sleep, waiting for the condition be true. • Block 될 수 있는 socket call • Input operations • read, readv, recv, recvfrom, recvmsg function • blocking TCP socket에 대해 위 함수들 중 하나를 호출한 경우socket receive buffer에 이용할 데이터가 없다면 데이터가 도착할 때 까지 sleep상태에 놓이게 됨 • readn function & MSG_WAITALL flag

  3. Introduction (cont.) • Output operations • write, writev, send, sendto, sendmsg function • 커널은 어플리케이션의 buffer로부터 socket send buffer로 데이터를 copy • blocking socket에서 socket send buffer에 공간이 없으면 프로세스는 공간이 생길 때까지 sleep상태 • nonblocking TCP socket에서는 socket send buffer에 전혀 공간이 없으면 즉시 EWOULDBLOCK Error를 리턴 • socket send buffer에 조금의 공간이라도 있으면 return value는 커널이 buffer로 copy할 수 있는 바이트의 수 (short count)

  4. Introduction (cont.) • Accepting incoming connections • accept function • accept가 blocking socket에 호출되고 새로운 연결이 유효하지 않으면 프로세스는 sleep상태 • accept가 nonblocking socket에 호출되고 새로운 연결이 유효하지 않으면 에러 EWOULDBLOCK가 리턴 • Initiating outgoing connections • connect function for TCP • connect함수는 클라이언트가 자신의 SYN에 대해 ACK를 받기 전까지는 리턴되지 않음 • TCP connect가 서버로의 왕복시간(RTT)동안 호출한 프로세스를 항상 봉쇄한다는 것을 의미 • connect가 nonblocking TCP socket에 호출되고 연결이 즉시 설정되지 않으면 연결 설정이 초기화되고 에러 EINPROGRESS가 리턴

  5. Introduction (cont.) • 위의 네 가지 모든 operation에 대한 예 제공 • nonblocking connect을 사용하여 여러 개의 TCP연결들을 동시에 시작하는 웹 클라이언트와 유사한 새로운 클라이언트 형 개발

  6. Nonblocking Reads and Writes : str_cli Function (Revisited) • 기존 str_cli함수 • blocking I/O을 사용함 • stdin에서 한 줄이 이용 가능하면 fgets로 읽어서 writen으로 서버에게 보냄 • 만약 소켓 송신 버퍼가 가득 차 있으면, writen호출은 block됨 • writen호출에서 block되어 있는 동안, data는 소켓 수신 버퍼로부터 읽기 가능함 • 이 절의 목표 • nonblock I/O을 사용하는 이 함수의 변형을 개발하는 것 • 생산적인 다른 일을 하는 동안 block되는 것을 방지 • Two buffer • to: standard input에서 server로 가는 데이터 포함 • fr: server로부터 standard output로 가는 데이터 포함

  7. stdin &to [MAXLINE] toiptr already send data to send to server available space to Read into form stdin to : tooptr socket Figure 16.1 Buffer containing data from standard input going to the socket. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) • Figure 16.1은 to 버퍼의 배열과 버퍼에 대한 포인터를 보여줌

  8. socket &fr [MAXLINE] friptr already send data to send to standard output available space to read into form socket fr : froptr stdout Figure 16.2 Buffer containing data from socket going to standard output. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) • Figure 16.2는 fr 버퍼의 대응되는 배열을 보여줌

  9. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) – strclinonb.c Figure 16.3 str_cli function, first part : initializes and calls select.

  10. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) – strclinonb.c Figure 16.4 str_cli function, second part : reads from standard input or socket.

  11. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) – strclinonb.c Figure 16.5 str_cli function, third part : writes to standard output or socket.

  12. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) – lib/gf_time.c • str_cli function에서 호출하는 gf_time function • 이 함수는 마이크로 초까지를 포함하는 현재의 시각의 문자열을 아래의 모양으로 리턴 • 12:34:56.123456 • tcpdump에 의한 timestamp와 의도적으로 동일한 모양 Figure 16.6 gt_time function : returns pointer to time string.

  13. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.)

  14. client to buffer socket send buffer socket receiver buffer client fr buffer server TCP segments TCP segments 3508 (write) 4096 (read) 4096 2636 4096 stdin 4096 (write) 4096 3508 (read) 1176 1460 1460 1460 1460 1460 588 1460 1460 1176 2636 1460 588 588 588 stdin stdout stdin stdout Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) Figure 16.8 Timeline of nonblocking example.

  15. one TCP connection (full-duplex) stdin parent server fork stdout child Figure 16.9 str_cli function using two processes. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) • A simple version of str_cli • TCP 연결은 전-이중이며 parent와 child는 동일한 소켓 번호를 공유한다. • 함수는 fork를 호출하여 parent와 child 프로세스로 나눈다 • child는 서버로부터 온 line들을 standard output로 copy • parent는 standard input으로부터의 line들을 서버로 복사 • parent는 소켓에 쓰고 child는 소켓으로부터 읽음

  16. Figure 16.10 Version of str_cli function that users fork. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) • A simple version of str_cli

  17. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) • Termination sequence • 정상적인 종료 • standard input에서 파일 끝을 만났을 경우에 발생 • parent는 파일의 끝(EOF) 을 읽고 FIN을 보내기 위해 shutdown을 호출 • 서버 프로세스가 이르게 종료할 때 • child는 소켓에서 파일 끝을 읽고 parent에게 standard input에서 소켓으로 복사하는 것을 멈추도록 알려주어야 함 • parent가 여전히 실행 중일 때 child는 parent에게 SIGTERM신호를 보냄 • 다른 방법: child가 종료하고 parent가 여전히 실행 중이면 parent가 SICHLD를 포착하도록 하는 것 • parent가 복사를 마쳤을 때 pause를 호출하는데 이런 경우 신호가 포착될 때까지 sleep상태가 유지됨 • parent가 아무런 신호도 포착하지 못하더라도 이것은 child로부터 SIGTERM신호를 받을 때까지 parent는 sleep 상태가 됨

  18. Nonblocking Reads and Writes : str_cli Function (Revisited) (cont.) • Timing of str_cli • 2000 line를 Solaris 클라이언트로부터 서버에 175ms RTT로 복사할 때에 각 버전들에 필요한 시간 • 354.0 sec, stop-and-wait (Figure 5.5) • 12.3 sec, select and blocking I/O (Figure 6.13) • 6.9 sec, nonblocking I/O (Figure 16.3) • 8.7 sec, fork (Figure 16.9) • 8.5 sec, threaded version (Figure 23.2) • nonblocking I/O 버전이 select와 blocking I/O를 사용한 버전보다 두 배 빠름 • fork를 사용한 간단한 버전이 nonblocking I/O보다 느리지만 코드의 복잡성이 덜함

  19. Nonblocking connect • 동작과정 • TCP소켓이 nonblocking으로 설정되고 connect를 호출하면, connect는 EINPROGRESS오류를 리턴 하지만 TCP three-way handshake는 계속 • 연결설정의 성공적 완료 여부는 select를 이용해 점검 • nonblocking connect의 세 가지 용도 • three-way handshake가 다른 프로세스와 overlap할 수 있음 • connect가 완료되는 동안 다른 프로세스를 수행 할 수 있음 • 이 기법을 이용해서 multiple-connection을 설정할 수 있음 • 웹 브라우저에서 널리 사용, 16.5절이 이것의 예 • select에서 시간 한계를 지정함으로써 connect의 시간 만료를 줄일 수 있음 • application이 더 짧은 timeout을 원할 때, nonblocking connect를 사용

  20. Nonblocking connect (cont.) • nonblocking에서 반드시 처리해야 할 세부적인 것 • 소켓이 nonblocking임에도 연결하려는 서버가 동일한 호스트에 있으면 연결 설정은 connect를 호출할 때 바로 이루어짐 . 이 scenario를 다룰 수 있어야 함 • 버클리 파생의 구현들은 (Posix) select와 nonblocking connect에 관련된 다음의 두 가지 규칙을 가지고 있다. • 연결이 성공적으로 마칠 때, descriptor는 쓰기 가능해지고 • 연결시에 오류가 발생하면, descriptor는 읽기와 쓰기가 동시에 가능해진다.

  21. Nonblocking connect : Daytime Client • Figure 16.11(450 page): nonblocking connect를 수행하는 connect_nonb함수 • Figure 1.5에서의 connect호출을 다음과 같이 바꿈 • 1~3번째 인수: connect의 정상적인 인수들 • 4번째 인수: 연결이 완료될 때까지 기다리는 초 길이 • 값이 0이면 select에 시간 만료가 없다는 것을 의미 • 따라서 커널은 일반적인 TCP 연결 설정 시간 만료 사용 if (connect_nonb(sockfd, (SA) &servaddr, sizeof(servaddr), 0) <0) err_sys(“connect error”);

  22. Nonblocking connect : Daytime Client (cont.)

  23. Figure 16.11 Issue a nonblocking connect. Nonblocking connect : Daytime Client (cont.)

  24. Nonblocking connect : Daytime Client (cont.) • Interrupted connect • TCP의 three-way handshake가 끝나기 전에 보통의 blocking socket에 대한 connect호출이 일시 중지되었을 때 • connect가 자동적으로 다시 시작되지 않는다고 가정하면 이것은 EINTR를 리턴 • 연결이 완료되기를 기다리기 위해 다시 connect를 다시 호출 할 수 없음, 그렇게 하면 EADDRINUSE를 리턴 • 해결방법: 이 절의 nonblocking connect에서 했던 것처럼 select를 호출

  25. Nonblocking connect : Web Client • nonblocking connect의 실질적인 예는 Netscape의 웹 클라이언트와 함께 시작됨 • 클라이언트는 웹 서버와 HTTP 연결을 맺고 홈페이지를 가져옴 : 그 페이지는 다름 웹페이지에 대한 많은 참조 • 하나씩 가져오는 대신 nonblocking connect를 사용하여 동시에 하나 이상을 가져옴 • Figure 16.12는 여러 개의 연결을 동시에 맺는 예제 • Figure 16.13는 처음 연결이 자체적으로 이루어진 후 처음 연결로부터의 데이터에서 발견된 여러 개의 참조를 위해 여러 개의 연결이 생김

  26. three connections done in parallel; maximum of three connections at a time three connections done in parallel; maximum of two connections at a time three connections done serially Figure 16.12 Establishing multiple connections in parallel. Figure 16.13 Complete first connection, then multiple connections in parallel. Nonblocking connect : Web Client (cont.)

  27. Figure 16.14 web.h header. Nonblocking connect : Web Client (cont.)

  28. Figure 16.15 First part of simultaneous connect: global and start of main. Nonblocking connect : Web Client (cont.)

  29. Figure 16.16 home_page function Nonblocking connect : Web Client (cont.) • Establish connection with server • 9 : tcp_connect는 서버와 연결을 맺음 • Send HTTP command to server; read reply • 11-22: HTTP GET 명령이 홈페이지에 대해 행해짐(종종 /라 부름), reply를 읽고 연결을 닫음

  30. Figure 16.17 Initiate nonblocking connect. Nonblocking connect : Web Client (cont.)

  31. Figure 16.18 Send an HTTP GET command to the server. Nonblocking connect : Web Client (cont.) • Build command and send it • 9-11: 명령을 만들고 소켓으로 씀 • 13-17: 파일의 F_READIING flag가 설정되면 F_CONNECTING flag가 해제 • main loop에게 descriptor 가 입력을 위해 준비되었다고 알려줌, 필요 시 read set으로 설정되고 maxfd가 갱신

  32. Nonblocking connect : Web Client (cont.)

  33. Figure 16.19 Main loop of main function. Nonblocking connect : Web Client (cont.)

  34. Figure 16.21 TCP echo client that creates connection and sends an RST Nonblocking accept if (FD_ISSET(listenfd, &rset)) { /* new client connection */ + printf(“listening socket readable \n”); + sleep(5); clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);

  35. Nonblocking accept (cont.) • 5.11절에서 서버가 accept를 호출하기 전에 클라이언트가 연결을 파기할 때, Berkeley-derived 구현은 파기한 연결을 서버에게 돌려주지 않는 반면 다른 구현은 ECONNABORTED를 리턴하거나 대신 EPROTO를 리턴 • Berkeley-derived 구현들을 고려 • 클라이언트는 연결 설정 후 Figure 16.21에서 처럼 그것을 취소함 • select가 서버 프로세스에게 읽기 가능이라고 리턴하지만 서버가 accept를 호출하는데 짧은 시간이 걸림 • 서버가 select로부터의 리턴과 accept를 호출 하는 것 사이에 RST를 클라이언트로부터 받음 • 완료된 연결이 대기열에서 제거되고 다른 완료된 연결은 존재하지 않는다고 가정 • 서버가 accept를 호출하지만 완료된 연결이 없기 때문에 block되게 됨

  36. Nonblocking accept (cont.) • 해결책 • 연결이 언제 accept될 준비가 되는지를 알려고 select를 사용하면, 항상 listening socket를 nonblocking으로 설정 • accept호출에서 다음의 오류 무시 • EWOULDBLOCK • Berkeley-derived 구현에서 클라이언트가 연결을 파기할 때 • ECONNABORTED • Posix.1g 구현에서 클라이언트가 연결을 파기할 때 • EPROTO • SVR4 구현에서 클라이언트가 연결을 파기할 때 • EINTR • 신호를 포착할 때

  37. Summary • 16.2절에의 nonblocking read와 write의 예제는 str_cli echo client를 택하여 서버로의 TCP연결에서 nonblocking I/O를 사용하도록 수정 • nonblocking connect는 TCP의 three-way handshake가 일어나는 동안 connect의 호출에서 block되는 대신 다른 process 처리 • 서버로부터 여러 파일을 가져오는 시간을 줄이기 위해 한번에 여러 개의 TCP 연결을 여는 웹 클라이언트 유사한 새로운 클라이언트를 개발하기 위해 nonblocking connect사용

More Related