Np unit iii

Np unit iii

  1. vamsitricks
    Np unit iii
    Transcript Header:
    Np unit iii
    Transcript Body:
    • 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 servers 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
    • 34. wait and waitpid Functions #include 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. > 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
    • 36. 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; }
    View More