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.
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 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 effective. By time consuming, we spend more than two days on finding out the calling sequence. By effective, 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.
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