First, when we use a single process single connection and use ReadLine modified client program, to connect using ReadLine Modified server-side program, there will be an interesting phenomenon, look at the output:
Run the server side first, then run the client,
simba@ubuntu:~/documents/code/linux_programming/unp/socket$./echoser_recv_peek
Recv Connect ip=127.0.0.1 port=54005
simba@ubuntu:~/documents/code/linux_programming/unp/socket$./echocli_recv_peek
Local ip=127.0.0.1 port=54005
You can look at the network status first,
simba@ubuntu:~$ Netstat-an | grep TCP | grep 5188
TCP 0 0 0.0.0.0:5188 0.0.0.0:* LISTEN
TCP 0 0 127.0.0.1:54005 127.0.0.1:5188 established
TCP 0 0 127.0.0.1:5188 127.0.0.1:54005 established
As you can see, the connection is established, with two processes on the server side, one in the listening state, and another child process servicing the client.
Then PS out the server-side subprocess and kill it,
simba@ubuntu:~$ Ps-ef | grep echoser
Simba 4549 3593 0 15:57 pts/0 00:00:00./echoser_recv_peek
Simba 4551 4549 0 15:57 pts/0 00:00:00./echoser_recv_peek
Simba 4558 4418 0 15:57 pts/6 00:00:00 grep--color=auto echoser
simba@ubuntu:~$ kill-9 4551
Then look at the network state,
simba@ubuntu:~$ Netstat-an | grep TCP | grep 5188
TCP 0 0 0.0.0.0:5188 0.0.0.0:* LISTEN
TCP 1 0 127.0.0.1:54005 127.0.0.1:5188 close_wait
TCP 0 0 127.0.0.1:5188 127.0.0.1:54005 fin_wait2
To analyze, we kill the server subprocess, when it terminates, the socket descriptor will automatically close the concurrent fin segment to client,client after receiving the fin in the close_wait state, but the client does not terminate, The socket descriptor is not closed, so the FIN is not sent to the server child process, so the TCP connection for the server subprocess is fin_wait2.
Why is this happening, to see the client part of the program:
void do_echocli (int sock)
{
char sendbuf[1024] = {0};
Char recvbuf[1024] = {0};
while (Fgets (sendbuf, sizeof (SENDBUF), stdin)!= NULL)
{
writen (sock, SendBuf, strlen (SendBuf));
int ret = ReadLine (sock, Recvbuf, sizeof (RECVBUF)); Read
if (ret = 1)
err_exit ("ReadLine error") by line;
else if (ret = 0) //server shuts down
{
printf ("Server close\n");
break;
Fputs (Recvbuf, stdout);
memset (sendbuf, 0, sizeof (SENDBUF));
memset (recvbuf, 0, sizeof (RECVBUF));
}
Close (sock);
}