Мультиплексирование ввода/вывода Программирование с использованием POSIX thread library.

Slides:



Advertisements
Similar presentations
ADVANCED NETWORK PROGRAMMING BİLGİN METİN ADVANCED SOCKET OPTIONS  IPv4&IPv6 Interoperability  IOCTL Options  Advanced I/O Functions  Nonblocking I/O.
Advertisements

1 Interprocess Communication CS 241 April 2, 2012 University of Illinois.
Threads Programming Thread creation Synchronization.
Sop, Fan Reference: Daniel Spangenberger Computer Networks PPT-4 Socket Programming.
I/O Models Satish Krishnan. I/O Models Blocking I/O Non-blocking I/O I/O Multiplexing Signal driven I/O Asynchronous I/O.
Returning to zombies and parents and children. –What happens to the children if the parent dies? /* ILLUSTRATING THAT UPON A PARENT KILL THE ZOMBIES /*
I/O Multiplexing: select and poll
Chapter 6 I/O Multiplexing: select and poll function.
I/O Multiplexing Road Map: 1. Motivation 2. Description of I/O multiplexing 3. Scenarios to use I/O multiplexing 4. I/O Models  Blocking I/O  Non-blocking.
1 Select and poll and Signals CS 241 April 6, 2012 University of Illinois.
Daemon Processes Long lived utility processes Often started at system boot and ended when system shuts down Run in the background with no controlling terminal.
Today’s topic Issues about sending structures with TCP. Server design alternatives: concurrent server and multiplexed server. I/O multiplexing.
Computer Networks Sockets. Sockets and the OS F An end-point for Internet connection –What the application “plugs into” –OS provides Application Programming.
Advanced Sockets Amit Mondal TA, Intro to Networking Jan 22, 2009 Recital 3 Introduction to Networking Instructor: Prof. Aleksandar Kuzmanovic.
I/O Multiplexing© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science.
Programming with Berkeley Sockets Presented by Chris GauthierDickey Written by Daniel Stutzbach (I think!) for CIS 432/532 Useful References: ● man pages.
Event-Driven Programming Vivek Pai Dec 5, GedankenBits  What does a raw bit cost?  IDE  40GB: $100  120GB: $180  32MB USB Pen: $38  FireWire:
1 Data Communications and Networking Socket Programming Part II: Design of Server Software Reference: Internetworking with TCP/IP, Volume III Client-Server.
I/O Multiplexing Capability of tell the kernel that wants to be notified when one or more I/O conditions are ready. For example, I/O data is available.
Winsock programming.  TCP/IP UDP TCP  Winsock #include wsock32.lib.
1 I/O Multiplexing Computer Network Programming. 2 Input from multiple sources Process keyboard sockets file A process may have multiple sources of input.
Introduction to Project 1 Web Client and Server Jan 2006.
Select The select function determines the status of one or more sockets, waiting if necessary, to perform synchronous I/O. int select( int nfds, fd_set*
Chapter 5. TCP Client-Server Example. Contents –Introduction –TCP Echo Server –TCP Echo Client –Normal Startup and Termination –Posix Signal Handling.
IP Multiplexing Ying Zhang EECS 489 W07.
CS4516: Medical Examiner Client/Server Evan Frenn 1.
Elementary UDP Sockets© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer.
1 TCP Client-Server Example TCP echo server: main and str_echo TCP echo client: main and str_cli Normal startup and termination POSIX signal handling Handling.
1 Non-blocking I/O Computing Network Programming.
Chapter 8 Elementary UDP Socket. Contents u recvfrom and sendto Function u UDP Echo Server( main, de_echo Function) u UDP Echo Client( main, de_cli Function)
1 Internet Socket programming Behzad Akbari. 2 Sharif University of Technology, Kish Island Campus What is an API? API – stands for Application Programming.
Socket programming. Sockets are a protocol independent method of creating a connection between processes. Sockets can be either: connection based or connectionless:
Concurrent Servers April 25, 2002 Topics Limitations of iterative servers Process-based concurrent servers Threads-based concurrent servers Event-based.
UNIX Network Programming1 Chapter 15. Nonblocking I/O.
Review: How to create a TCP end point? What is the right format for sin_port and sin_addr in the sockaddr_in data structure? How many different ways we.
TELE 402 Lecture 4: I/O multi … 1 Overview Last Lecture –TCP socket and Client-Server example –Source: Chapters 4&5 of Stevens’ book This Lecture –I/O.
Chapter18 broadcasting. contents Introduction broadcast address unicast versus broadcast dg_cli function using broadcasting Race conditions.
1 COMP/ELEC 429/556 Introduction to Computer Networks Creating a Network Application Some slides used with permissions from Edward W. Knightly, T. S. Eugene.
Socket Programming Lec 2 Rishi Kant. Review of Socket programming Decide which type of socket – stream or datagram. Based on type create socket using.
CSCE 515: Computer Network Programming Select Wenyuan Xu Department of Computer Science and Engineering.
I/O Multiplexing. TCP Echo Client: I/O operation is sequential !! tcpcliserv/tcpcli01.c: lib/str_cli.c: TCP Client TCP Server stdin stdout fgets fputs.
Threads and Locking Ioctl operations. Threads Lightweight processes What’s wrong with processes? –fork() is expensive – 10 to 100 times slower –Inter.
Threads Chapter 26. Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is.
I/O Multiplexing. What is I/O multiplexing? When an application needs to handle multiple I/O descriptors at the same time –E.g. file and socket descriptors,
CONCURRENT PROGRAMMING Lecture 5. 2 Assignment 1  Having trouble?  Resolve it as early as possible!  Assignment 2:  Handling text-based protocol 
PA3: Improving Performance with I/O Multiplexing Part 1-1: Nov. 7, Part 1-2: Nov. 10 Part 2-1: Nov. 17, Part 2-2: Nov.20.
Single Process, Concurrent, Connection-Oriented Servers (TCP) (Chapter 12)
Introduction A Simple Daytime Client A Simple Daytime Server
CMPT 471 Networking II Network Programming © Janice Regan,
UNIX Network Programming1 Chapter 13. Advanced I / O Functions.
回到第一頁 Client/sever model n Client asks (request) – server provides (response) n Typically: single server - multiple clients n The server does not need.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
[Unix Programming] Interprocess Communication - PIPE Young-Ju, Han
@Yuan Xue CS 283Computer Networks Spring 2013 Instructor: Yuan Xue.
Mgr inż. Marcin Borkowski UNIX Pipe and FIFO. mgr inż. Marcin Borkowski Waiting for I/O ● Pipes, FIFO's, sockets and stdin usually can not produce data.
More Project 1 and HW 1 stuff! Athula Balachandran Wolfgang Richter
I/O Multiplexing.
Concurrent Servers December 7, 2000
Chapter 5. TCP Client-Server Example
Socket programming Péter Verhás August 2002
Elementary UDP Sockets
Review: TCP Client-Server Interaction
Imam Ahmad Trinugroho, ST., MMSI
Sockets, part 2 (Addresses, poll())
CISC2200 Threads Spring 2015.
Advanced Sockets Introduction to Networking
Lecture 4 Socket Programming Issues
Chapter 5 (part 1) TCP Client /Server Example By: Lim Meng Hui.
Lecture 11 Overview.
Elementary UDP Sockets connectionless, unreliable, datagram
Presentation transcript:

Мультиплексирование ввода/вывода Программирование с использованием POSIX thread library

select(3C) #include int select(int nfds, fd_set *restrict readfds, fd_set *restrict writefds, fd_set *restrict errorfds, struct timeval *restrict timeout); nfds – это максимальный номер дескриптора во всех наборах

fd_set Описывает множество дескрипторов файлов Номер дескриптора не может быть больше, чем FD_SETSIZE На 32-битных платформах FD_SETSIZE==1024 На 64-битном Solaris FD_SETSIZE==65536 void FD_SET(int fd, fd_set *fdset); void FD_CLR(int fd, fd_set *fdset); int FD_ISSET(int fd, fd_set *fdset); void FD_ZERO(fd_set *fdset);

readfds, writefds, errorfds Входные и выходные параметры readfds –дескрипторы, годные для чтения –дескрипторы, где достигнут конец файла (e.q. закрытые на другом конце трубы и сокеты) –слушающие сокеты (accept) ^^^ это нельзя понять, это можно только запомнить writefds –дескрипторы, годные для записи (write не заблокируется) –для сокетов гарантируется запись SO_SNDLOWAT байт –закрытые на другом конце трубы и сокеты errorfds –зависит от типа устройства, напр. для регулярных файлов не используется –для сокетов TCP/IP – приход внеполосных данных (URGENT)

struct timeval long tv_sec; long tv_usec; Если timeout==NULL, ждать бесконечно Если timeout->tv_sec/tv_usec==0, работает в режиме опроса (возвращается немедленно) В остальных случаях обозначает таймаут (максимальное время ожидания) Может модифицироваться при успешном завершении

Пример использования #include"unp.h" void str_cli(FILE *fp, int sockfd) { intmaxfdp1, stdineof; fd_setrset; charsendline[MAXLINE], recvline[MAXLINE]; stdineof = 0; FD_ZERO(&rset); for ( ; ; ) { if (stdineof == 0) FD_SET(fileno(fp), &rset); FD_SET(sockfd, &rset); maxfdp1 = max(fileno(fp), sockfd) + 1; Select(maxfdp1, &rset, NULL, NULL, NULL); if (FD_ISSET(sockfd, &rset)) {/* socket is readable */ if (Readline(sockfd, recvline, MAXLINE) == 0) { if (stdineof == 1) return;/* normal termination */ else err_quit("str_cli: server terminated prematurely"); } Fputs(recvline, stdout); } if (FD_ISSET(fileno(fp), &rset)) { /* input is readable */ if (Fgets(sendline, MAXLINE, fp) == NULL) { stdineof = 1; Shutdown(sockfd, SHUT_WR);/* send FIN */ FD_CLR(fileno(fp), &rset); continue; } Writen(sockfd, sendline, strlen(sendline)); }

poll(2) #include int poll(struct pollfd fds[], nfds_t nfds, int timeout); nfds – это количество дескрипторов в fds

struct pollfd int fd; /* file descriptor */ short events; /* requested events */ short revents; /* returned events */ POLLIN (== POLLRDNORM | POLLRDBAND ) –для слушающих сокетов означает готовность accept POLLOUT POLLERR (только в revents) POLLHUP (только в revents) POLLNVAL (только в revents)

Пример использования #include struct pollfd fds[3]; int ifd1, ifd2, ofd, count; fds[0].fd = ifd1; fds[0].events = POLLNORM; fds[1].fd = ifd2; fds[1].events = POLLNORM; fds[2].fd = ofd; fds[2].events = POLLOUT; count = poll(fds, 3, 10000); if (count == -1) { perror("poll failed"); exit(1); } if (count==0) printf("No data for reading or writing\n"); if (fds[0].revents & POLLNORM) printf("There is data for reading fd %d\n", fds[0].fd); if (fds[1].revents & POLLNORM) printf("There is data for reading fd %d\n", fds[1].fd); if (fds[2].revents & POLLOUT) printf("There is room to write on fd %d\n", fds[2].fd);

poll(7d) Solaris only (начиная с Solaris 7) #include int fd = open("/dev/poll", O_RDWR); ssize_t n = write(int fd, struct pollfd buf[], int bufsize); Pollfd.events=POLLREMOVE; int n = ioctl(int fd, DP_POLL, struct dvpoll* arg); int n = ioctl(int fd, DP_ISPOLLED, struct pollfd* pfd);

Преимущества poll(7d) Данные для Solaris 7 bash-2.03$ a.out 4000 poll Opened 4000 file descriptor(s) Starting write / [poll|ioctl] / read loop: write()/poll()/read()s on 4000 fd(s) took : msec. bash-2.03$ a.out 4000 devpoll Opened 4000 file descriptor(s) Starting write / [poll|ioctl] / read loop: write()/ioctl(DP_POLL)/read()s on 4000 fd(s) took : 2179 msec.