Chapter 5. TCP Client-Server

Similar documents
Semester 2, Computer Communication 352 Module 4

UNIT III - APPLICATION DEVELOPMENT. TCP Echo Server

Lecture 3 Overview! Last Lecture! TCP/UDP and Sockets introduction!

UNIX System Programming. Overview. 2. Signal Types (31 in POSIX) Signal Sources. Signals. 1. Definition

Signals. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Announcement (1) Due date for PA3 is changed (~ next week) PA4 will also be started in the next class. Not submitted. Not scored

Advanced Unix/Linux System Program. Instructor: William W.Y. Hsu

Inter-process communication (IPC)

CSci 4061 Introduction to Operating Systems. (Advanced Control Signals)

Multitasking. Programmer s model of multitasking. fork() spawns new process. exit() terminates own process

CSC209H Lecture 8. Dan Zingaro. March 4, 2015

Preview. The pause() System Call. The pause() System Call. The signal() System Call 10/18/2017

CS 33. Signals Part 1. CS33 Intro to Computer Systems XXII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Processes, Signals, I/O, Shell Lab : Introduc>on to Computer Systems Recita>on 9: Monday, Oct. 21, 2013 Marjorie Carlson Sec>on A

CS 550 Operating Systems Spring Inter Process Communication

CSCI 4061: Signals and Signal Handlers

CONCURRENCY MODEL. UNIX Programming 2014 Fall by Euiseong Seo

Overview. Administrative. * HW 1 grades. * HW 2 Due. Topics. * 5.1 What is a Signal? * Dealing with Signals - masks, handlers

Programming Assignments will be.. All the PAs are continuous 3 major factors that you should consider

Signals. CSC209: Software Tools and Systems Programming. Furkan Alaca & Paul Vrbik

Signals. Joseph Cordina

Processes & Signals. System Runs Many Processes Concurrently. State consists of memory image + register values + program counter

Piotr Mielecki Ph. D.

Experiential Learning Workshop on Basics of Socket Programming

Shell Execution of Programs. Process Groups, Session and Signals 1

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 20

Computer Systems Laboratory Sungkyunkwan University

CS631 - Advanced Programming in the UNIX Environment. Process Groups, Sessions, Signals

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430

Unix Network Programming Chapter 4. Elementary TCP Sockets 광운대학교컴퓨터과학과 정보통신연구실 석사과정안중현

n Unconditionally kill process 8371 n Interactive interrupt key n See /usr/include/bits/signum.h (e.g., SIGKILL 9) 2 -Ken Wong, Sep 2008

Operating System Structure

Operating Systems. Lecture 05

系統程式 郭大維教授 / 施吉昇教授臺灣大學資訊工程系

Exceptions, Processes and Signals

Lesson 3. The func procedure allows a user to choose the action upon receipt of a signal.

#include <dirent.h> int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); DIR *opendir(const char *name);

Lecture 4. Introduction to Unix Processes. Introduction to Systems Programming: Processes and Signals

Acontecimentos assíncronos (POSIX signals) Sincronização com múltiplos acontecimentos

Kernel and processes

Preview. Process Termination. wait and waitpid() System Call. wait and waitpid() System Call. waitpid() System Call 10/23/2018

Process Management. Outline

Concurrent Programming. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Unix-Linux 2. Unix is supposed to leave room in the process table for a superuser process that could be used to kill errant processes.

CSE 421: Introduction to Operating Systems

CS240: Programming in C

Introduction to Client-Server Model

Lecture 24: Multitasking and Signals

Shell and Signals. Computer Organization 3/17/2015. CSC252 - Spring The World of Multiprogramming or Multitasking. Unix Process Hierarchy

Process. Signal #8. Signals are software interrupts from unexpected events. a power failure. an alarm clock. the death of a child process

CS213. Exceptional Control Flow Part II. Topics Process Hierarchy Signals

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

Basic POSIX signal concepts

Week 13. Final exam review

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid.

Concurrent Servers Dec 2, 2009"

Exceptional Control Flow Exists at All Levels of a System. Systemprogrammering 2007 Föreläsning 3 Exceptional Control Flow Part II

CSC209H Lecture 11. Dan Zingaro. March 25, 2015

Process Management! Goals of this Lecture!

Introduction to Processes

Exceptional Control Flow Part II

Lesson 2. process id = 1000 text data i = 5 pid = 1200

System Programming. Process Control II

Workshop on Inter Process Communication Solutions

Carnegie Mellon. Bryant and O Hallaron, Computer Systems: A Programmer s Perspective, Third Edition

Signals are a kernel-supported mechanism for reporting events to user code and forcing a response to them. There are actually two sorts of such

call connect call read call connect ret connect call fgets Client 2 blocks waiting to complete its connection request until after lunch!

Recitation Processes, Signals,UNIX error handling

Operating Systems 2010/2011

Network Programming. Multicast on a LAN 1/4. Sending & Receiving Multicast Messages. Multicasting II. Dr. Thaier Hayajneh

Lecture #23 Concurrent Programming

Parameter Passing in C. Pointer Arithmetic. Parameter Passing in C. Pointer Arithmetic. Pointer Arithmetic. Tevfik Ko!ar

Giving credit where credit is due

CSC209 Review. Yeah! We made it!

ECF Exists at All Levels of a System Exceptional Control Flow Part II Oct. 22, 2002 Topics! Process Hierarchy! Shells! Signals!

Process Management 1

Contents. IPC (Inter-Process Communication) Representation of open files in kernel I/O redirection Anonymous Pipe Named Pipe (FIFO)

Pipes and FIFOs. Woo-Yeong Jeong Computer Systems Laboratory Sungkyunkwan University

Recitation 8 Processes, Signals, Tshlab

A read or write being atomic means that its effect is as if it happens instantaneously.

CS240: Programming in C

Preview. Interprocess Communication with Pipe. Pipe from the Parent to the child Pipe from the child to the parent FIFO popen() with r Popen() with w

Signals. POSIX defines a variety of signal types, each for a particular

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 19

Signals! Goals of this Lecture! Help you learn about:" Sending signals" Handling signals"

Process Management! Goals of this Lecture!

Discussion of Assignments 2. Line buffered vs. full buffered I/O. Some often encountered issues in the submissions.

Exceptional Control Flow Part I

System Programming 熊博安國立中正大學資訊工程學系

Exceptional Control Flow: Signals and Nonlocal Jumps

Signals. Goals of this Lecture. Help you learn about: Sending signals Handling signals

CSC209 Fall Karen Reid 1

Each terminal window has a process group associated with it this defines the current foreground process group. Keyboard-generated signals are sent to

Exceptional Control Flow Part I

Elementary TCP Sockets

Any of the descriptors in the set {1, 4} have an exception condition pending

UNIX Processes. by Armin R. Mikler. 1: Introduction

Parents and Children

Lecture 4. Introduction to make Debugging with gdb and ddd Introduction to Systems Programming: Processes and Signals

Transcription:

Chapter 5. TCP Client-Server Example

Contents Introduction TCP Echo Server TCP Echo Client Normal Startup and Termination Posix Signal Handling Handling SIGCHLD Signals Data Format and so on...

5.1 Introduction stdin stdout fgets fputs TCP client writen readline readline writen TCP server 1. The Client reads a line of text from its standard input and writes the line to the server. 2. The server reads the line from its network input and echoes the line back to the client. 3. The client reads the echoed line and prints it on its standard output.

5.2 TCP Echo Server main function & str_echo function for ( ; ; ) { clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *) &cliaddr, &clilen); if ( (childpid = Fork()) == 0) {/* child process */ Close(listenfd);/* close listening socket */ str_echo(connfd);/* process the request */ exit(0); } Close(connfd); /* parent closes connected socket */ }

void str_echo(int sockfd) { ssize_t n; char line[maxline]; for ( ; ; ) { } if ( (n = Readline(sockfd, line, MAXLINE)) == 0) return; /* connection closed by other end */ Writen(sockfd, line, n); }

5.4 TCP Echo Client main function & str_cli function Connect(sockfd, (SA *) &servaddr, sizeof(servaddr)); str_cli(stdin, sockfd); /* do it all */ exit(0);

TCP echo client

void str_cli(file *fp, int sockfd) { char sendline[maxline], recvline[maxline]; while (Fgets(sendline, MAXLINE, fp)!= NULL) { Writen(sockfd, sendline, strlen(sendline)); if (Readline(sockfd, recvline, MAXLINE) == 0) err_quit("str_cli: server terminated prematurely"); } Fputs(recvline, stdout); }

Normal Startup How the client and server start, how they end What happens when something goes wrong the client host crashes, the client process crashes, network connectivity is lost Test method tcpserv & netstat -a tcpcli 127.0.0.1 (local test) netstat -a ps -l

Normal Termination tcpcli 127.0.0.1 hello, world hello, world good bye good bye ^D netstat -a grep procid ps 19130 p1 Ss -ksh 21130 p1 I./tcpserv 21132 p1 Z (tcpserv) (Z:zombie process)

5.8 Posix Signal Handling A signal (software interrupt) : a notification to a process that an event has occurred. Signals can be sent by one process to another process(or itself) by the kernel to a process SIGCHLD signal: a signal sent by the kernel whenever a process terminates, to the parent of the terminating process

Every signal has a disposition (action associated with the signal) We can provide a function hat is called whenever a specific signal occurs. This function is called a signal handler and this action is called catching the signal. (SIGKILL(x) and SIGSTOP(X)), void handler(int signo); We can ignore a signal by setting its disposition to SIG_IGN. (SIGKILL(x) and SIGSTOP(X)), We can set the default disposition for a signal by setting its disposition to SIG_DFL. (terminate a process on the receipt of a signal) SIGCHLD(X), SIGURG(x)

5.8 Posix Signal Handling signal Function Sigfunc * signal(int signo, Sigfunc *func) { struct sigaction act, oact; } act.sa_handler = func; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (signo == SIGALRM) { #ifdef SA_INTERRUPT act.sa_flags = SA_INTERRUPT; /* SunOS 4.x */ #endif } else { #ifdef SA_RESTART act.sa_flags = SA_RESTART; /* SVR4, 44BSD */ #endif } if (sigaction(signo, &act, &oact) < 0) return(sig_err); return(oact.sa_handler);

5.8 Posix Signal Handling 2-3 normal function prototype void (*signal(int signo, void (*func) (int) ) ) (int); define Sigfunc type in unp.h header typedef void Sigfunc(int); The function prototype Sigfunc *signal(int signo, Sigfunc *func); 6 : The sa_handler member of the sigaction structure is set to the func argument. members of sigaction structure void (*) (int) sa_handler sigset_t sa_mask int sa_flag

5.8 Posix Signal Handling 7 : Set signal mask for handler Posix allow us to specify a set of signals that will be blocked when our signal handler is called. Any signal that is blocked cannot be delivered to the process. #include <signal.h> int sigaddset(sigset_t *set, int signo); int sigemptyset(sigset_t *set); int sigfillset(sigset_t *set); int sigdelset(sigset_t *set, int signo); int sigismember(sigset_t *set, int signo); int sigprocmask(int how, const sigset_t *set, sigset_t *oset); SIG_BLOCK SIG_SETMASK SIG_UNBLOCK

5.8 Posix Signal Handling SIGALRM place a timeout on an I/O operation SA_RESTART a system call interrupted by this signal will be automatically restarted by the kernel

5.8 Posix Signal Handling Posix Signal Semantics Once a signal handler is installed, it remains installed. While a signal handler is executing, the signal being delivered is blocked. If a signal is generated one or more times while it is blocked, it is normally delivered only one time after the signal is unblocked. That is, by default Unix signals are not queued. It is possible to selectively block and unblock a set of signals using the sigprocmask function.

Handling SIGCHLD Signals Zombie State maintain information about the child for the parent to fetch at some later time the process ID of the child, its termination status, the resource of the child(cpu time, memory) the parent process ID of all the zombie children: 1(init process)-inherit the children and clean them up <defunct> Handling Zombies space waste of the kernel, out of process wait for the children to prevent them from becoming zombies

Handling SIGCHLD Signals We establish the signal handler by adding the function call Signal (SIGCHLD, sig_chld); in Figure 5.2, after the call to listen. #include "unp.h" void sig_chld(int signo) { pid_t pid; int stat; pid = wait(&stat); printf("child %d terminated\n", pid); return; } Figure 5.7 Version of SIGCHLD signal handler that calls wait

Tcpserv02 & tcpcli01 127.0.0.1 hi, there hi, there ^D child 16942 terminated accept error: Interrupted system call // the parent is blocked in its call to accept when the SIGCHLD is delivered //sig_chld function executes, wait fetches the child PID and termination status, printf // kernel causes the accept to return an error of EINTER

5.9 Handling SIGCHLD Signals Handling Interrupted System Calls for ( ; ; ) { } clilen = sizeof(cliaddr); if( (connfd=accept(listenfd,(sa *) &cliaddr,&clilen)) < 0) { if( errno == EINTER ) else continue; err_sys( accept error );

5.10 wait and waitpid #include <sys/wait.h> pid_t wait(int *statloc); Functions pid_t waitpid(pid_t pid, int *statloc, int option); pid_t: the process ID of the terminated child statloc : the termination status of the child(an integer) is returned through the statloc pointer. pid : specify the process ID that we want to wait for. A value of -1 say to wait for the first of our children to terminate. option : specify additional option. The most common option is WNOHANG.

>tcpserv03 & >tcpcli03 206.62.226.35 hello hello ^D child 21288 terminated 21282 p1 S./tcpserv03 21284 p1 Z (tcpcli03) 21285 p1 Z (tcpcli03) 21286 p1 Z (tcpcli03) 21287 p1 Z (tcpcli03)

5.10 wait and waitpid Functions Difference between wait and waitpid the problem is that all five signals are generated before the signal handler is executed, and the signal handler is executed only one time because Unix signals are normally not queued. waitpid we must specify the WNOHANG option: this tells waitpid not to block if there exist running children that have not yet terminated. void sig_chld(int signo) { pid_t pid; int stat; } while((pid = waitpid(-1,&stat,wnohang)) > 0) printf("child %d terminated\n", pid); return;

5.11 Connection Abort before accept Returns The three-way handshake completes, the connection is established, and then the client TCP sends an RST(reset). On the server side the connection is queued by its TCP, waiting for the server process to call accept when the RST arrives. Some time later the server process calls accept.

Implementation BSD : kernel SVR4 : return an errno of EPROTO Posix.1g : return an errno of ECONNABORTED EPROTO : returned when some fatal protocol-related events occur on the streams subsystem. In the case of the ECONNABORTED error, the server can ignore the error and just call accept again.

5.12 Termination of Server Process solaris % tcpcli01 206.62.226.35 hello hello another line str_cli: server terminated prematurely Our client is not expecting to receive an end-offile at this point so it quits with the error message server terminated prematurely.

SIGPIPE Signal What happens if the client the error return from readline and writes more data to the server? When a process writes to a socket that has received an RST, the SIGPIPE signal is sent to the process Default action of SIGPIPE: terminate the process

>tcpcli11 206.62.226.34 hi there hi there bye Nothing is echoed for bye data Reason: the default action of SIGPIPE is terminate the process.

What happens when the server host crashes, reboots, shutdowns