Symptom:
Recently, we are experiencing process hang with the GoAhead Web server. the symptom can be reproduced if we disconnect the network cable while the browser is loading a page. when it occurs, we can see that the process doesn't occupy any CPU resource with top command. and we can see there are a lot of connections in established, close_wait, time_wait, fin_wait status with netsstat-ATN command.
Ayalysis:
From the symptom we observed, there is no doubt it's caused by process hang. usually, process hang is caused by the process being waiting on some conditions never or take an extreme long time to satisfy. A typical scenario is dead lock.
We adopted a method that is kind of naive but straightforward to investigate the cause, which is printf. we inserted a lot of printf statement into source code to find out exactly in which method did the Web server hanged. this is time consuming but yet valid tive. by time consuming, we spend more than two days on finding out the calling sequence. by using tive, we finally find out that the Web server is hanging in network operation.
ASIDE: It does seems inefficient to do so. actually, we 've tried to attach a debugger to the Hung process with gdbserver (CMD: gdbserver -- attach IPaddress: Port PID ). but in the debugger, it seems to be missing correct symbol information. and even the thread information (CMD: info threads) isn' t correct. these information are correct if we attach the debugger to the Web server when it's not hung.
The real cause is when the Peer of the socket is forcibly disconnected even without sending fin. so the Web server still considers the socket in established state. then it will operate on the socket as normal. if the socket is in blocking mode and doesn't have a timeout specified, the web server will be blocked on reading from or writting to the socket indefinitely.
Solution:
Having found out the cause, it's easy to solve it. we can either specify a timeout on the native socket or set the socket to non-blocking mode. code below demonstrates how to achieve so.
1. Specify timeout
Void webssslreadevent (webs_t WP)
{
Sptr = socketprt (WP-> Sid );
Struct timeval TV;
TV. TV _sec = 2; // timeout is two seconds
TV. TV _usec = 0; // It must be set to 0 explicitly, otherwise it may be a random number
Int rc = setsockopt (sptr-> sock, sol_socket, so_rcvtimeo, (struct timeval *) & TV, sizeof (struct timeval ));
Rc = setsockopt (sptr-> sock, sol_socket, so_sndtimeo, (struct timeval *) & TV, sizeof (struct timeval ));
....
}
2. Clear Blocking Mode
Void websdone (webs_t WP)
{
....
Socketsetblock (WP-> Sid, 0); // The second parameter is one originally. So that it will flush everything to the peer in blocking mode to achieve graceful closing
Socketflush (WP-> Sid );
}