SlideShare une entreprise Scribd logo
1  sur  38
 Contents

    Introduction
    TCP Echo Server
    TCP Echo Client
    Normal Startup and Termination
    Handling SIGCHLD Signals
Introductioon

            fgets
    stdin                     writen    readline
                    TCP                             TCP
   stdout           client   readline    writen    server
            fputs


  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.
TCP Echo Server: main Function

   Create socket, bind server's well-known
    port
   Wait for client connection to complete
   Concurrent server
   G:echo_server.c
TCP Echo Server: str_echo Function
   Read a buffer and echo the buffer
   str_echo function: echoes data on a socket
   #include "unp.h"
   void str_echo(int sockfd)
    { ssize_t n;
    char buf[MAXLINE];
   again:
    while ( (n = read(sockfd, buf, MAXLINE)) > 0)
   Writen(sockfd, buf, n);
    if (n < 0 && errno == EINTR)
    goto again;
    else if (n < 0)
    err_sys("str_echo: read error");
    }
TCP echo client.

   Create socket, fill in Internet socket
    address structure
   Connect to server
   G:echo_client.c.txt
TCP Echo Client: str_cli Function

   Read a line, write to server
   Read echoed line from server, write to
    standard output
   Return to main
str_cli function: client processing loop.

   #include "unp.h"
   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
 what happens when something goes wrong: the
  client host crashes, the client process crashes,
  network connectivity is lost
 % tcpserv01 &

 % netstat -a

 Active Internet connections (servers and established)
    Proto    Recv-Q   Send-Q   Local Address   Foreign Address
     State
    tcp        0        0         *:9877         *:*
     LISTEN
Normal Startup
   linux % tcpcli01 127.0.0.1

   When the three-way handshake completes, connect returns in
    the client and accept returns in the server.

   The connection is established. The following steps then take
    place:

   The client calls str_cli, which will block in the call to fgets,
    because we have not typed a line of input yet.
Normal Startup
   When accept returns in the server, it calls fork and the
    child calls str_echo. This function calls readline, which
    calls read, which blocks while waiting for a line to be sent
    from the client.

   The server parent, on the other hand, calls accept again,
    and blocks while waiting for the next client connection.
Normal Startup
   % netstat -a
   Active Internet connections (servers and established)
   Proto Recv-Q Send-Q Local Address                Foreign Address       State
    tcp         0        0        local host:9877    localhost:42758 ESTABLISHED
      tcp         0        0        local host:42758 localhost:9877
    ESTABLISHED tcp             0          0       *:9877              *:*
      LISTEN

% ps -t pts/6 -o pid,ppid,tty,stat,args,wchan
  PID         PPID        TT       STAT      COMMAND         WCHAN
 22038       22036       pts/6       S           –bash      wait4
 17870       22038       pts/6       S        ./tcpserv01 wait_for_connect
 19315       17870       pts/6       S        ./tcpserv01    tcp_data_wait
 19314       22038       pts/6       S        ./tcpcli01127.0 read_chan
Normal Termination
   % tcpcli01 127.0.0.1              we showed this line earlier

hello, world                       we now type this
hello, world                       and the line is echoed
good bye
good bye
^D                         Control-D is our terminal EOF character
Steps involved in the normal termination
of our client and server:
   When we type our EOF character, fgets returns a null pointer
    and the function str_cli returns.

   When str_cli returns to the client main function ,the latter
    terminates by calling exit.

   Part of process termination is the closing of all open descriptors,
    so the client socket is closed by the kernel.
Steps involved in the normal termination of
our client and server:
   When the server TCP receives the FIN, the server child
    is blocked in a call to readline ,and readline then returns
    0.

   The server child terminates by calling exit.

   All open descriptors in the server child are closed.

   The SIGCHLD signal is sent to the parent when the
    server child terminates.
   linux % ps -t pts/6 -o pid,ppid,tty,stat,args,wchan
   PID     PPID    TT      STAT   COMMAND          WCHAN
    22038   22036   pts/6     S      - bash         read_chan
    17870   22038   pts/6     S    ./tcpserv01   wait_for_connect
    19315   17870   pts/6     Z      tcpserv01     <defu do_exit
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.
Connection Abort before accept Returns

   Berkeley-derived implementations handle the aborted connection
    completely within the kernel, and the server process never sees it.

   Most SVR4 implementations, however, return an error to the process as
    the return from accept, and the error depends on the implementation.

   These SVR4 implementations return an errno of EPROTO ("protocol
    error"),

   But POSIX specifies that the return must be ECONNABORTED
    ("software caused connection abort") instead.
Connection Abort before accept Returns

   The reason for the POSIX change is that EPROTO is also returned
    when some fatal protocol-related events occur on the streams
    subsystem.

   Returning the same error for the nonfatal abort of an established
    connection by the client makes it impossible for the server to know
    whether to call accept again or not.

   In the case of the ECONNABORTED error, the server can ignore
    the error and just call accept again.
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-of-file at this
    point so it quits with the error message “server
    terminated prematurely”.
Termination of Server Process
   We start the server and client and type one line

   kill child process. All open descriptors in the child are closed.
    This causes a FIN to be sent to the client, and the client TCP
    responds with an ACK.

   The SIGCHLD signal is sent to the server parent and handled
    correctly.
Termination of Server Process
   Nothing happens at the client. The client TCP receives
    the FIN from the server TCP and responds with an ACK,

   client process is blocked in the call to fgets waiting for a
    line from the terminal.

   Type a line of input to the client

   Client can send data but server can not…
Termination of Server Process
   The server TCP responds with an RST

   The client process will not see the RST because it calls
    readline immediately after the call to writen and readline
    returns 0 (EOF) immediately because of the FIN that was
    received in Step 2.

   client quits with the error message "server terminated
    prematurely."
Termination of Server Process

   When the client terminates , all its open descriptors are closed.

   The client's call to readline may happen before the server's RST is
    received by the client, or it may happen after. But if the RST
    arrives first, the result is an ECONNRESET ("Connection reset by
    peer") error return from readline.
Crashing of Server Host
   Disconnect server host from he network and type another line at the
    client.

   When the server host crashes, nothing is sent out on the existing
    network connections.

   We type a line of input to the client. The client then blocks in the call
    to readline, waiting for the echoed reply.

   we will see the client TCP continually retransmitting the data
    segment, trying to receive an ACK from the server.
Crashing of Server Host
   Berkeley-derived implementations retransmit the data segment 12
    times, waiting for around 9 minutes before giving up. When the
    client TCP finally gives up an error is returned to the client
    process.

   Since the client is blocked in the call to readline, it returns an
    error. Assuming the server host crashed and there were no
    responses at all to the client's data segments, the error is
    ETIMEDOUT.

   But if some intermediate router determined that the server host
    was unreachable and responded with an ICMP "destination
    unreachable' message, the error is either EHOSTUNREACH or
    ENETUNREACH.
Crashing and Rebooting of Server Host
   We start the server and then the client. We type a line to verify
    that the connection is established.

   The server host crashes and reboots.

   We type a line of input to the client, which is sent as a TCP
    data segment to the server host.

   When the server host reboots after crashing, its TCP loses all
    information about connections that existed before the crash.
    Therefore, the server TCP responds to the received data
    segment from the client with an RST.

   Our client is blocked in the call to readline when the RST is
    received, causing readline to return the error ECONNRESET.
Shutdown of Server Host
   When a Unix system is shut down,

   The init process normally sends the SIGTERM signal to all
    processes ,waits some fixed amount of time ,and then sends the
    SIGKILL signal to any processes still running.

   This gives all running processes a short amount of time to clean up
    and terminate.

   If we do not catch SIGTERM and terminate, our server will be
    terminated by the SIGKILL signal.

   When the process terminates, all open descriptors are closed.
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 that 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),
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 terminatedn", 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
Handling SIGCHLD Signals
   Handling Interrupted System Calls

     for ( ; ; ) {
        clilen = sizeof(cliaddr);
        if( (connfd=accept(listenfd,(SA *)
        &cliaddr,&clilen)) < 0) {
              if( errno == EINTER )
                     continue;
              else
                     err_sys(“accept error”);
     }
wait and waitpid Functions
       #include <sys/wait.h>

       pid_t wait(int *statloc);

       pid_t waitpid(pid_t pid, int *statloc, int option);
   pit_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 &              21282   p1 S ./tcpserv03
>tcpcli03 206.62.226.35   21284   p1 Z (tcpcli03)
 hello                    21285   p1 Z (tcpcli03)
 hello                    21286   p1 Z (tcpcli03)
 ^D                       21287   p1 Z (tcpcli03)
 child 21288 terminated
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.
       we cannot call wait in a loop, because there is no way to prevent wait from blocking if
        there are running children that have not yet terminated.

   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 terminatedn", pid);
                  return;
            }
Np unit iii

Contenu connexe

Tendances

Tendances (20)

Chapter 4 a interprocess communication
Chapter 4 a interprocess communicationChapter 4 a interprocess communication
Chapter 4 a interprocess communication
 
TCP IP Addressing
TCP IP AddressingTCP IP Addressing
TCP IP Addressing
 
SPAN, RSPAN and ERSPAN
SPAN, RSPAN and ERSPANSPAN, RSPAN and ERSPAN
SPAN, RSPAN and ERSPAN
 
BOOTP and DHCP.ppt
BOOTP and DHCP.pptBOOTP and DHCP.ppt
BOOTP and DHCP.ppt
 
Computer network
Computer networkComputer network
Computer network
 
11. dfs
11. dfs11. dfs
11. dfs
 
Clientserver Presentation
Clientserver PresentationClientserver Presentation
Clientserver Presentation
 
TCP/IP 3-way Handshake
TCP/IP 3-way Handshake TCP/IP 3-way Handshake
TCP/IP 3-way Handshake
 
Naming in Distributed System
Naming in Distributed SystemNaming in Distributed System
Naming in Distributed System
 
CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMS
 
Cisco Networking (Routing and Switching)
Cisco Networking (Routing and Switching)Cisco Networking (Routing and Switching)
Cisco Networking (Routing and Switching)
 
Cs8493 unit 4
Cs8493 unit 4Cs8493 unit 4
Cs8493 unit 4
 
What is Ping
What is PingWhat is Ping
What is Ping
 
program flow mechanisms, advanced computer architecture
program flow mechanisms, advanced computer architectureprogram flow mechanisms, advanced computer architecture
program flow mechanisms, advanced computer architecture
 
Address resolution protocol (ARP)
Address resolution protocol (ARP)Address resolution protocol (ARP)
Address resolution protocol (ARP)
 
Replication in Distributed Systems
Replication in Distributed SystemsReplication in Distributed Systems
Replication in Distributed Systems
 
Chapter 06 - Routing
Chapter 06 - RoutingChapter 06 - Routing
Chapter 06 - Routing
 
Transport layer services
Transport layer servicesTransport layer services
Transport layer services
 
Network monitoring system
Network monitoring systemNetwork monitoring system
Network monitoring system
 
Peer to Peer services and File systems
Peer to Peer services and File systemsPeer to Peer services and File systems
Peer to Peer services and File systems
 

Similaire à Np unit iii

CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdfsecunderbadtirumalgi
 
13_TCP_Attack.pptx
13_TCP_Attack.pptx13_TCP_Attack.pptx
13_TCP_Attack.pptxAlmaOraevi
 
Web and internet technology notes for BCA students
Web and internet technology notes for BCA studentsWeb and internet technology notes for BCA students
Web and internet technology notes for BCA studentsnawejakhatar10063
 
Client server examples for tcp abnormal conditions
Client server examples for tcp abnormal conditionsClient server examples for tcp abnormal conditions
Client server examples for tcp abnormal conditionsCEC Landran
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure CallNadia Nahar
 
Running Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docx
Running Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docxRunning Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docx
Running Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docxjoellemurphey
 
Lecture 5
Lecture 5Lecture 5
Lecture 5ntpc08
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using CAjit Nayak
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded wsmile790243
 
Socket programming
Socket programmingSocket programming
Socket programmingAnurag Tomar
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxkacie8xcheco
 
Socket网络编程
Socket网络编程Socket网络编程
Socket网络编程qhm123
 
How packet data travel over network
How packet data travel over networkHow packet data travel over network
How packet data travel over networkRaisa Anjani
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxRockyBhai46825
 

Similaire à Np unit iii (20)

CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
 
13_TCP_Attack.pptx
13_TCP_Attack.pptx13_TCP_Attack.pptx
13_TCP_Attack.pptx
 
Web and internet technology notes for BCA students
Web and internet technology notes for BCA studentsWeb and internet technology notes for BCA students
Web and internet technology notes for BCA students
 
Client server examples for tcp abnormal conditions
Client server examples for tcp abnormal conditionsClient server examples for tcp abnormal conditions
Client server examples for tcp abnormal conditions
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure Call
 
Running Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docx
Running Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docxRunning Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docx
Running Head CLIENT SERVER AUTHENTICATIONHANDLING CONCURRENT CL.docx
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
#1 (TCPvs. UDP)
#1 (TCPvs. UDP)#1 (TCPvs. UDP)
#1 (TCPvs. UDP)
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
Rpc
RpcRpc
Rpc
 
Socket网络编程
Socket网络编程Socket网络编程
Socket网络编程
 
How packet data travel over network
How packet data travel over networkHow packet data travel over network
How packet data travel over network
 
Lecture9
Lecture9Lecture9
Lecture9
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 

Plus de vamsitricks (20)

Unit 6
Unit 6Unit 6
Unit 6
 
Np unit1
Np unit1Np unit1
Np unit1
 
Np unit iv i
Np unit iv iNp unit iv i
Np unit iv i
 
Np unit iv ii
Np unit iv iiNp unit iv ii
Np unit iv ii
 
Unit 7
Unit 7Unit 7
Unit 7
 
Npc16
Npc16Npc16
Npc16
 
Npc14
Npc14Npc14
Npc14
 
Npc13
Npc13Npc13
Npc13
 
Unit 3
Unit 3Unit 3
Unit 3
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 7
Unit 7Unit 7
Unit 7
 
Unit 6
Unit 6Unit 6
Unit 6
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit4wt
Unit4wtUnit4wt
Unit4wt
 
Unit3wt
Unit3wtUnit3wt
Unit3wt
 
Unit2wt
Unit2wtUnit2wt
Unit2wt
 
Unit 1wt
Unit 1wtUnit 1wt
Unit 1wt
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Jsp with mvc
Jsp with mvcJsp with mvc
Jsp with mvc
 

Np unit iii

  • 1.  Contents  Introduction  TCP Echo Server  TCP Echo Client  Normal Startup and Termination  Handling SIGCHLD Signals
  • 2. Introductioon fgets stdin writen readline TCP TCP stdout client readline writen server fputs 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.
  • 3. TCP Echo Server: main Function  Create socket, bind server's well-known port  Wait for client connection to complete  Concurrent server  G:echo_server.c
  • 4. TCP Echo Server: str_echo Function  Read a buffer and echo the buffer  str_echo function: echoes data on a socket  #include "unp.h"  void str_echo(int sockfd)  { ssize_t n;  char buf[MAXLINE];  again:  while ( (n = read(sockfd, buf, MAXLINE)) > 0)  Writen(sockfd, buf, n);  if (n < 0 && errno == EINTR)  goto again;  else if (n < 0)  err_sys("str_echo: read error");  }
  • 5. TCP echo client.  Create socket, fill in Internet socket address structure  Connect to server  G:echo_client.c.txt
  • 6. TCP Echo Client: str_cli Function  Read a line, write to server  Read echoed line from server, write to standard output  Return to main
  • 7. str_cli function: client processing loop.  #include "unp.h"  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);  }  }
  • 8. Normal Startup  what happens when something goes wrong: the client host crashes, the client process crashes, network connectivity is lost  % tcpserv01 &  % netstat -a Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 *:9877 *:* LISTEN
  • 9. Normal Startup  linux % tcpcli01 127.0.0.1  When the three-way handshake completes, connect returns in the client and accept returns in the server.  The connection is established. The following steps then take place:  The client calls str_cli, which will block in the call to fgets, because we have not typed a line of input yet.
  • 10. Normal Startup  When accept returns in the server, it calls fork and the child calls str_echo. This function calls readline, which calls read, which blocks while waiting for a line to be sent from the client.  The server parent, on the other hand, calls accept again, and blocks while waiting for the next client connection.
  • 11. Normal Startup  % netstat -a  Active Internet connections (servers and established)  Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 local host:9877 localhost:42758 ESTABLISHED tcp 0 0 local host:42758 localhost:9877 ESTABLISHED tcp 0 0 *:9877 *:* LISTEN % ps -t pts/6 -o pid,ppid,tty,stat,args,wchan PID PPID TT STAT COMMAND WCHAN 22038 22036 pts/6 S –bash wait4 17870 22038 pts/6 S ./tcpserv01 wait_for_connect 19315 17870 pts/6 S ./tcpserv01 tcp_data_wait 19314 22038 pts/6 S ./tcpcli01127.0 read_chan
  • 12. Normal Termination  % tcpcli01 127.0.0.1 we showed this line earlier hello, world we now type this hello, world and the line is echoed good bye good bye ^D Control-D is our terminal EOF character
  • 13. Steps involved in the normal termination of our client and server:  When we type our EOF character, fgets returns a null pointer and the function str_cli returns.  When str_cli returns to the client main function ,the latter terminates by calling exit.  Part of process termination is the closing of all open descriptors, so the client socket is closed by the kernel.
  • 14. Steps involved in the normal termination of our client and server:  When the server TCP receives the FIN, the server child is blocked in a call to readline ,and readline then returns 0.  The server child terminates by calling exit.  All open descriptors in the server child are closed.  The SIGCHLD signal is sent to the parent when the server child terminates.
  • 15. linux % ps -t pts/6 -o pid,ppid,tty,stat,args,wchan  PID PPID TT STAT COMMAND WCHAN 22038 22036 pts/6 S - bash read_chan 17870 22038 pts/6 S ./tcpserv01 wait_for_connect 19315 17870 pts/6 Z tcpserv01 <defu do_exit
  • 16. 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.
  • 17. Connection Abort before accept Returns  Berkeley-derived implementations handle the aborted connection completely within the kernel, and the server process never sees it.  Most SVR4 implementations, however, return an error to the process as the return from accept, and the error depends on the implementation.  These SVR4 implementations return an errno of EPROTO ("protocol error"),  But POSIX specifies that the return must be ECONNABORTED ("software caused connection abort") instead.
  • 18. Connection Abort before accept Returns  The reason for the POSIX change is that EPROTO is also returned when some fatal protocol-related events occur on the streams subsystem.  Returning the same error for the nonfatal abort of an established connection by the client makes it impossible for the server to know whether to call accept again or not.  In the case of the ECONNABORTED error, the server can ignore the error and just call accept again.
  • 19. 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-of-file at this point so it quits with the error message “server terminated prematurely”.
  • 20. Termination of Server Process  We start the server and client and type one line  kill child process. All open descriptors in the child are closed. This causes a FIN to be sent to the client, and the client TCP responds with an ACK.  The SIGCHLD signal is sent to the server parent and handled correctly.
  • 21. Termination of Server Process  Nothing happens at the client. The client TCP receives the FIN from the server TCP and responds with an ACK,  client process is blocked in the call to fgets waiting for a line from the terminal.  Type a line of input to the client  Client can send data but server can not…
  • 22. Termination of Server Process  The server TCP responds with an RST  The client process will not see the RST because it calls readline immediately after the call to writen and readline returns 0 (EOF) immediately because of the FIN that was received in Step 2.  client quits with the error message "server terminated prematurely."
  • 23. Termination of Server Process  When the client terminates , all its open descriptors are closed.  The client's call to readline may happen before the server's RST is received by the client, or it may happen after. But if the RST arrives first, the result is an ECONNRESET ("Connection reset by peer") error return from readline.
  • 24. Crashing of Server Host  Disconnect server host from he network and type another line at the client.  When the server host crashes, nothing is sent out on the existing network connections.  We type a line of input to the client. The client then blocks in the call to readline, waiting for the echoed reply.  we will see the client TCP continually retransmitting the data segment, trying to receive an ACK from the server.
  • 25. Crashing of Server Host  Berkeley-derived implementations retransmit the data segment 12 times, waiting for around 9 minutes before giving up. When the client TCP finally gives up an error is returned to the client process.  Since the client is blocked in the call to readline, it returns an error. Assuming the server host crashed and there were no responses at all to the client's data segments, the error is ETIMEDOUT.  But if some intermediate router determined that the server host was unreachable and responded with an ICMP "destination unreachable' message, the error is either EHOSTUNREACH or ENETUNREACH.
  • 26. Crashing and Rebooting of Server Host  We start the server and then the client. We type a line to verify that the connection is established.  The server host crashes and reboots.  We type a line of input to the client, which is sent as a TCP data segment to the server host.  When the server host reboots after crashing, its TCP loses all information about connections that existed before the crash. Therefore, the server TCP responds to the received data segment from the client with an RST.  Our client is blocked in the call to readline when the RST is received, causing readline to return the error ECONNRESET.
  • 27. Shutdown of Server Host  When a Unix system is shut down,  The init process normally sends the SIGTERM signal to all processes ,waits some fixed amount of time ,and then sends the SIGKILL signal to any processes still running.  This gives all running processes a short amount of time to clean up and terminate.  If we do not catch SIGTERM and terminate, our server will be terminated by the SIGKILL signal.  When the process terminates, all open descriptors are closed.
  • 28. 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
  • 29. Every signal has a disposition (action associated with the signal)  We can provide a function that 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),
  • 30. 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
  • 31. 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 terminatedn", pid); return; } Figure 5.7 Version of SIGCHLD signal handler that calls wait
  • 32. 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
  • 33. Handling SIGCHLD Signals  Handling Interrupted System Calls for ( ; ; ) { clilen = sizeof(cliaddr); if( (connfd=accept(listenfd,(SA *) &cliaddr,&clilen)) < 0) { if( errno == EINTER ) continue; else err_sys(“accept error”); }
  • 34. wait and waitpid Functions #include <sys/wait.h> pid_t wait(int *statloc); pid_t waitpid(pid_t pid, int *statloc, int option);  pit_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.
  • 35.
  • 36. >tcpserv03 & 21282 p1 S ./tcpserv03 >tcpcli03 206.62.226.35 21284 p1 Z (tcpcli03) hello 21285 p1 Z (tcpcli03) hello 21286 p1 Z (tcpcli03) ^D 21287 p1 Z (tcpcli03) child 21288 terminated
  • 37. 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.  we cannot call wait in a loop, because there is no way to prevent wait from blocking if there are running children that have not yet terminated.  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 terminatedn", pid); return; }