Ignore the SIGCHLD signal and give it to the kernel to process the subprocess, avoiding the zombie process.
Server-side:
1#include <iostream>2#include <netinet/inch.h>3#include <cstring>4#include <unistd.h>5#include <signal.h>6 7 #defineMAXLINE 40968 9 intMainintargcChar**argv) {Ten One signal (SIGCHLD, sig_ign); A intLISTENFD,CONNFD; - structsockaddr_in servaddr; - Charbuff[4096]; the intN; - - if(LISTENFD = socket (Af_inet,sock_stream,0)) == -1){ -printf"Create Socket error:%s (errno:%d) \ n", Strerror (errno), errno); + return 0; - } + Amemset (&SERVADDR,0,sizeof(SERVADDR)); atservaddr.sin_family =af_inet; -SERVADDR.SIN_ADDR.S_ADDR =htonl (inaddr_any); -Servaddr.sin_port = htonl (6666); - - if(Bind (LISTENFD, (structsockaddr*) &servaddr,sizeof(SERVADDR)) == -1){ -printf"bind socket Error:%s (errno:%d) \ n", Strerror (errno), errno); in return 0; - } to + if(Listen (LISTENFD,Ten) == -1){ -printf"Listen socket error:%s (errno:%d) \ n", Strerror (errno), errno); the return 0; * } $ Panax Notoginsengprintf"======waiting for client ' s request======\n"); - while(1){ the + if(CONNFD = Accept (LISTENFD, (structsockaddr*) (null,null)) = =-1){ A theprintf"Accept Socket error:%s (errno:%d) \ n", Strerror (errno), errno); + Continue; - $ } $PID =fork (); - if(PID = =-1) -Err_exit ("Fork Error"); the if(PID = =0) - {Wuyi the Close (LISTENFD); - while(1){ Wun = recv (Connfd,buff,maxline,0); -Buff[n] =' /'; Aboutprintf"recv msg from client:%s\n", buff); $ Close (CONNFD); - } - exit (exit_success); - } A Else + Close (conn); the } - $ return 0; the } the
Client:
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <errno.h>5#include <sys/types.h>6#include <sys/socket.h>7#include <netinet/inch.h>8#include <arpa/inet.h>9#include <unistd.h>Ten #defineMAXLINE 4096 One A intMainintargcChar**argv) { - intsockfd, N; - Charrecvline[4096], sendline[4096]; the structsockaddr_in servaddr; - - if(ARGC! =2){ -printf"usage:./client <ipaddress>\n"); + return 0; - } + A if(SOCKFD = socket (af_inet, Sock_stream,0)) <0){ atprintf"Create socket Error:%s (errno:%d) \ n", Strerror (errno), errno); - return 0; - } - -memset (&SERVADDR,0,sizeof(SERVADDR)); -servaddr.sin_family =af_inet; inServaddr.sin_port = htons (6666); - if(Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <=0){ toprintf"Inet_pton error for%s\n", argv[1]); + return 0; - } the * if(Connect (SOCKFD,structsockaddr*) &servaddr,sizeof(SERVADDR)) <0){ $printf"Connect Error:%s (errno:%d) \ n", Strerror (errno), errno);Panax Notoginseng return 0; - } the +printf"send msg to server: \ n"); AFgets (Sendline,4096, stdin); the if(Send (SOCKFD, Sendline, strlen (Sendline),0) <0){ +printf"Send msg Error:%s (errno:%d) \ n", Strerror (errno), errno); - return 0; $ } $ Close (SOCKFD); - return 0; -}
TCP Programming: Multi-process (fork) concurrent processing of client requests