TDC561 Network Programming Camelia Zlatea, PhD Week 3: Unix Asynchronous Events; Signals and Alarms API.

Slides:



Advertisements
Similar presentations
Nonblocking I/O Blocking vs. non-blocking I/O
Advertisements

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.
Today’s topic Issues about sending structures with TCP. Server design alternatives: concurrent server and multiplexed server. I/O multiplexing.
Lecture 12 Overview. UDP Connected mode A UDP socket can be used in a call to connect() This simply tells the O.S. the address of the peer No handshake.
Lecture 16 Overview. Creating a TCP socket int bind(int sockfd, const struct sockaddr *myaddr, socklen_t addrlen); int mysock; struct sockaddr_in myaddr;
Computer Networks Sockets. Sockets and the OS F An end-point for Internet connection –What the application “plugs into” –OS provides Application Programming.
Operating Systems, Spring 2002 Ittai Abraham, Zinovi Rabinovich (recitation)
1 Processes and Pipes COS 217 Professor Jennifer Rexford.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
Page 1 Task Control: Signals and Alarms Chapter 7 and 8 B. Ramamurthy.
I/O Multiplexing© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science.
Signals Hua LiSystems ProgrammingCS2690Signals. Topics: Sending Signals -- kill(), raise() Signal Handling -- signal() sig_talk.c -- complete example.
Programming with Berkeley Sockets Presented by Chris GauthierDickey Written by Daniel Stutzbach (I think!) for CIS 432/532 Useful References: ● man pages.
TDC368 UNIX and Network Programming
Operating Systems Course Hebrew University Spring 2007 Signals & User Thread.
1 Data Communications and Networking Socket Programming Part II: Design of Server Software Reference: Internetworking with TCP/IP, Volume III Client-Server.
Home: Phones OFF Please Unix Kernel Parminder Singh Kang Home:
3.5 Interprocess Communication
CS Lecture 16 Outline Inter-process Communication (IPC) – Pipes – Signals Lecture 161CS Operating Systems 1.
Signal Signal : - is a notification sent to a process to notify it of some event - interrupts whatever the process is doing and force it to handle a signal.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
Lecture 8 UDP Sockets & I/O Multiplexing
IP Multiplexing Ying Zhang EECS 489 W07.
UNIX Signals Bach 7.2 Operating Systems Course The Hebrew University Spring 2010.
1 CS503: Operating Systems Part 1: OS Interface Dongyan Xu Department of Computer Science Purdue University.
1Reference “Introduction To Unix Signals Programming” in the reference material section Man page – sigprocmask, alarm “Understanding the Linux Kernel”
Operating Systems Chapter 2
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
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.
* POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm Topics.
Agenda  Working with Processes: Purpose Running Programs within same process (execl, execlp, execle, execv, execvp, execve) “Spawning” other process (fork,
1 I/O Multiplexing We often need to be able to monitor multiple descriptors:We often need to be able to monitor multiple descriptors: –a generic TCP client.
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.
CE Operating Systems Lecture 13 Linux/Unix interprocess communication.
Unix Process Model Simple and powerful primitives for process creation and initialization. fork syscall creates a child process as (initially) a clone.
CSCE 515: Computer Network Programming UDP Socket Wenyuan Xu Department of Computer Science and Engineering.
UNIX Socket Programming CS 6378 Project Reference Book: Unix Network programming: Networking APIs: Sockets and XTI (2nd edition), Prentice Hall >> Threads.
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,
Concurrency & Context Switching Process Control Block What's in it and why? How is it used? Who sees it? 5 State Process Model State Labels. Causes of.
Outline for Today Objectives –Finish discussion of Birrell –UNIX Signals –Eraser Administrative –Spider talk after class.
Signals and Signal Handling. Signals A predefined message sent between two processes or from the kernel to a process, or by a user to a process A software.
Signals (Chap 10 in the book “Advanced Programming in the UNIX Environment”) Acknowledgement : Prof. Y. Moon at Kangwon Nat’l Univ.
NCHU System & Network Lab Lab #8 Signals Operating System Lab.
1 Signals (continued) CS 241 April 9, 2012 University of Illinois.
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
UNIX Signals * POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm * Interval Timers * POSIX.1b Timers *
Operating Systems Recitation 4, April th, 2002 Signals.
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 14 Threads 2 Read Ch.
Single Process, Concurrent, Connection-Oriented Servers (TCP) (Chapter 12)
© 숙대 창병모 1 제 10 장 신호 (Signal). © 숙대 창병모 2 Contents 1. Signal Concepts 2. signal() 3. Interrupted System Calls 4. kill() /raise() 5. alarm() pause() 6.
CMPT 471 Networking II Network Programming © Janice Regan,
Today’s topics Signals and how to control the program behavior in handling signals. Terminal I/O.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
CSCI 330 UNIX and Network Programming Unit XVII: Socket Programming Detail.
1 Lecture 19: Unix signals and Terminal management n what is a signal n signal handling u kernel u user n signal generation n signal example usage n terminal.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Signals.
Client-Server Programming and Applications. References Douglas Comer, David Stevens, “Internetworking with TCP/IP: Client-Server Programming and Applications”,
G.Jyostna.
I/O Multiplexing.
Protection of System Resources
Review: TCP Client-Server Interaction
Lecture 4 Socket Programming Issues
Lecture 11 Overview.
Socket Programming.
Signals.
I/O Multiplexing We often need to be able to monitor multiple descriptors: a generic TCP client (like telnet) need to be able to handle unexpected situations,
Chapter 4: Threads.
Presentation transcript:

TDC561 Network Programming Camelia Zlatea, PhD Week 3: Unix Asynchronous Events; Signals and Alarms API Server Concurrency: Select () ; I/O Multiplexing;

Network Programming (TDC561)Page 2 Winter 2003 References  W. Richard Stevens, Network Programming : Networking API: Sockets and XTI, Volume 1, 2nd edition, 1998 (ISBN X) –Chap. 6 ( I/O Multiplexing)  John Shapley Gray, Interprocess Communications in UNIX - - The Nooks and Crannies Prentice Hall PTR, NJ, 1998 –Chap. 2, 4 (signals); Chap 10.6 ( I/O Multiplexing )  Douglas Comer, David Stevens, Internetworking with TCP/IP : Client-Server Programming, Volume III (BSD Unix and ANSI C), 2nd edition, 1996 (ISBN X) –Chap. 3,4,5

Unix System Programming - Topics Asynchronous Events Signals; Alarms;

Network Programming (TDC561)Page 4 Winter 2003 Asynchronous Events  Examples of process events: –a signal from another process –an interrupt from a device –completion of a I/O request  Signals are events delivered to a process via UNIX. The process has no control over when they arrive. Signals are understood as software version of hardware interrupts.  Signals can be generated by: –hardware: ex: division by zero, illegal address access –kernel: ex: completion of a I/O request issued by the waiting process –user processes: ex: communication among processes related to relevant events, child termination notified to parent –user actions: ex: pressing the keyboard sequence for: quit, interrupt  To find the current mapping of the key sequences for various signals, call shell command: stty -a –Example: SIGINT is mapped to "ctrl + c" (or DEL)

Network Programming (TDC561)Page 5 Winter 2003 Unix System Calls to handle signals  Signal system call is used to install signal handlers. /* legacy UNIX API */ #include void (*signal(int signo, void (*handler)(int)))(int); #include void (*sigset (int sig_no, void (*handler)(int)))(int); – The second parameter of the signal system call is a pointer to a function that returns void and takes a single integer as its argument, and the return value of signal itself is a pointer to a function that returns void and takes a single integer argument. – The second parameter to signal is a pointer to the function to call whenever the signal is delivered. – The return value is the previous signal handler that was installed before the new one was added.

Network Programming (TDC561)Page 6 Winter 2003 Signal Acceptance  Signals can be generated by outside events.  When a process receives a signal then the following actions can be taken: 1.ignore the signal 2.terminate the process (the default action SIG_DFL) 3.process the signal - take a particular action

Network Programming (TDC561)Page 7 Winter 2003 Signal Acceptance 1.Ignore the signal Program that ignores control-C. When an INT signal (control-C) is Received, the process ignores it (SIG_IGN is the handler) #include int main (void) { signal (SIGINT, SIG_IGN); while(1) { printf("Hello\n"); }

Network Programming (TDC561)Page 8 Winter 2003 Signal Acceptance 2. Terminate the process (the default action SIG_DFL) Default action (see manual pages man signal) is the action executed if nothing else #include int main() { signal(SIGINT, SIG_DFL); /* catch signal SIGINT=2 */ pause(); /* wait for a signal interruption */ }

Network Programming (TDC561)Page 9 Winter 2003 Signal Acceptance 3. Handle the signal - Take a particular action »The target process executes the action associated with the signal. »Processing the signal depends also on the state of the process and level of priority. Signals can be caught by specifying a signal catching routine. »The signals SIGKILL and SIGSTOP are never caught and they always terminate a process. #include void action (int sig){ signal (SIGINT, action); printf ("control-C won't stop this process!\n"); } int main (void){ signal (SIGINT, action); while(1) { printf("Hello\n"); }

Network Programming (TDC561)Page 10 Winter 2003 Signal Handling Example #include /* signal handler function */ void action(int sig_no) { signal(sig_no, action); fprintf(stderr,"Catch signal: %d\n", sig_no); } int main() { signal(SIGINT, action); signal(SIGALRM, SIG_DFL); signal(SIGTERM, SIG_IGN); pause(); /* wait for a signal interruption */ }

Network Programming (TDC561)Page 11 Winter 2003 Alarm Handling  Alarm system function  Sets a timer for the caller process and generates SIGALRM (signal number 14) after the specified number of seconds have passed. #include unsigned alarm(unsigned nosec);

Network Programming (TDC561)Page 12 Winter 2003 Alarm Handling  Example, alarm system calls cannot be stacked: int main(void) { alarm(20); while (1) fprintf(stderr,"Hello\n"); } alarm(10); alarm(20); // when this system call is invoked // the previous pending // alarm signal is canceled; // the timer is set to 20sec alarm(0); // this system call reset the timer, // any pending alarm system call is canceled

Network Programming (TDC561)Page 13 Winter 2003 Example of Handling Time-out Situations #include int main(void) { char buf[256]; int n; signal(SIGALRM, timeout); alarm(30); // set timer while ((n=read(0,buf,sizeof(buf))<0) ; alarm(0); // reset timer exit(0); } void timeout() { fprintf(stderr,"Timeout error\n"); exit(0); }

Network Programming (TDC561)Page 14 Winter 2003 Server Concurrency  For Servicing Multiple Clients there are two main approaches: –forking with fork() –selecting with select()  fork() approach forks a new process to handle each incoming client connection –Issues with zombies created when parent loops back to accept() a new client (ignore SIGCHILD signal) –Inefficient ( high overhead due to context switching)  A better approach would be to have a single process handle all incoming clients, without having to spawn separate child “server handlers”. select().

Network Programming (TDC561)Page 15 Winter 2003 I/O Multiplexing  Monitoring multiple descriptors: –a server that handles both TCP and UDP –a generic TCP client (like telnet) need to be able to handle unexpected situations, such as a server that shuts down without warning. »Input from standard input should be sent to a TCP socket. »Input from a TCP socket should be sent to standard output. –Non-determinism and Concurrency Problem: »How do we know when to check for input from each source?

Network Programming (TDC561)Page 16 Winter 2003 Solutions for Concurrency and I/O Non-determinism  Use nonblocking I/O –use fcntl() to set O_NONBLOCK  Use alarm and signal handler to interrupt slow system calls.  Use multiple processes/threads.  Use functions that support checking of multiple input sources at the same time.

Network Programming (TDC561)Page 17 Winter 2003 Non blocking I/O  use fcntl() to set O_NONBLOCK: #include int flags; flags = fcntl(sock,F_GETFL,0); fcntl(sock,F_SETFL,flags | O_NONBLOCK);  Now calls to read() (and other system calls) will return an error and set errno to EWOULDBLOCK.

Network Programming (TDC561)Page 18 Winter 2003 while (! done) { if ( (n=read(STDIN_FILENO,…)<0)) if (errno != EWOULDBLOCK) /* ERROR */ else write(tcpsock,…) if ( (n=read(tcpsock,…)<0)) if (errno != EWOULDBLOCK) /* ERROR */ else write(STDOUT_FILENO,…) }

Network Programming (TDC561)Page 19 Winter 2003 The problem with nonblocking I/O  Using blocking I/O allows the Operating System to put the process to sleep when nothing is happening (no input). Once input arrives the OS will wake up the process and read() (or write() … ) will return.  With nonblocking I/O the process will “busy-wait”, using inefficiently the CPU time

Network Programming (TDC561)Page 20 Winter 2003 Using alarms  Time-out handling with alarms signal(SIGALRM, sig_alrm); alarm(MAX_TIME); read(STDIN_FILENO,…);... signal(SIGALRM, sig_alrm); alarm(MAX_TIME); read(tcpsock,…);...  Issues: –How to assess the impact on response time ? –How to choose the value for MAX_TIME?

Network Programming (TDC561)Page 21 Winter 2003 Handling Timeout when calling recvfrom() Network Programming Aspects:  Nondeterministic delay, when calling recvfrom() can be limited by generating an alarm signal after a specified period of time (even if there is no incoming datagram.)  We can do this by using SIGALRM and wrapping each call to recvfrom() with a call to alarm()

Network Programming (TDC561)Page 22 Winter 2003 Handling Timeout when calling recvfrom() signal(SIGALRM, sig_alrm); alarm(max_time_to_wait); if (recvfrom(…)<0) if (errno==EINTR) /* timed out */ else /* some other error */ else /* no error or time out - turn off alarm */ alarm(0);

Network Programming (TDC561)Page 23 Winter 2003 select()  The select() system call allows us to use blocking I/O on a set of descriptors (file, socket, …).  For example, we can ask select to notify us when data is available for reading on either STDIN or a TCP socket.

Network Programming (TDC561)Page 24 Winter 2003 select() int select( int maxfd, fd_set *readset, fd_set *writeset, fd_set *excepset, const struct timeval *timeout);  The select() system call provides a way for a single server to wait until a set of network connections has data available for reading  The advantage over fork() here is that no multiple processes are spawned  The downside is that the single server must handle state management on its own for all its new clients –Finite State Machine Client/Server Model

Network Programming (TDC561)Page 25 Winter 2003 select() #include int select( int maxfd, fd_set *readset, fd_set *writeset, fd_set *excepset, const struct timeval *timeout); maxfd: highest number assigned to a descriptor. readset: set of descriptors we want to read from. writeset: set of descriptors we want to write to. excepset: set of descriptors to watch for exceptions/errors. timeout: maximum time select should wait

Network Programming (TDC561)Page 26 Winter 2003 select()  select() will return if any of the descriptors in readset and writeset of file descriptors are ready for reading or writing, respectively, or, if any of the descriptors in exceptset are in an error condition  The FD_SET(int fd, fd_set *set) function will add the file descriptor fd to the set set  The FD_ISSET(int fd, fd_set *set) function will tell you if filedescriptor fd is in the modified set set  select() returns the total number of descriptors in the modified sets  If a client closes a socket whose file descriptor is in one of your watched sets, select() will return, and your next recv() will return 0, indicating the socket has been closed

Network Programming (TDC561)Page 27 Winter 2003 Setting the timeval in select()  Setting the timeout to 0, select() times out immediately  Setting the timeout to NULL, select() will never time out, and will block indefinitely until a file descriptor is modified  To ignore a particular file descriptor set, just set it to NULL in the call: select (max, &readfds, NULL, NULL, NULL); –Here we only care about reading, and we want to block indefinitely until we do have a file descriptor ready to be read

Network Programming (TDC561)Page 28 Winter 2003 struct timeval struct timeval { long tv_sec;/* seconds */ long tv_usec;/* microseconds */ } struct timeval max = {1,0};

Network Programming (TDC561)Page 29 Winter 2003 fd_set  Implementation is not important  Operations to use with fd_set: void FD_ZERO( fd_set *fdset); void FD_SET( int fd, fd_set *fdset); void FD_CLR( int fd, fd_set *fdset); int FD_ISSET( int fd, fd_set *fdset);

Network Programming (TDC561)Page 30 Winter 2003 Using select()  Create fd_set  Clear the whole set with FD_ZERO  Add each descriptor you want to watch using FD_SET.  Call select  when select returns, use FD_ISSET to see if I/O is possible on each descriptor.

Other Unix API Timers, Errors

Network Programming (TDC561)Page 32 Winter 2003 Standard C library functions  - declares set of functions for system clock query time - #sec since 01/01/70 (UNIX birth) ctime - current local time localtime gmtime asctime mktime clock - (ANSI C), #microsec since the process first called clock

Network Programming (TDC561)Page 33 Winter 2003 Example: // evaluate process execution time --- C++ #include main() { time_t tick = CLOCKS_PER_SECOND; clock_t start_time = clock(); // start timer /* process code here */ clock_t duration = clock() - start_time; cout <<“Duration:”<<(duration/tick)<<endl; }