5. Volume 1 (Socket Networking API) --- TCP Client/Server Program Example

1. The blocking process catches the signal and returns with a slow system call that may return an EINTR error.
  Properly handle slow system calls:
	for ( ; ; ) {
		clilen = sizeof(cliaddr);
		if ( ( conndf = accpet(listenfd, (SA *)&cliaddr, &clilen) < 0 ) ) {
			if ( errno == EINTR ) {
				continue;
			} else {
				err_sys("accept error");
			}
		}
	}

2. In Unix, signals are not generally queued, and signal processing functions are generally executed only once.
  Use waitpid(), not wait. waitpid function, specifying the WNOHANG option, if any
  Do not block while a child process that has not yet terminated is running.
3. When writing a network program, there are three situations that may be encountered:
	1. When fork child process, SIGCHILD signal must be captured;
	2. When capturing the signal, the interrupted system call must be handled;
	3. The signal handler for SIGCHILD must be written correctly, and the waitpid function should be used to avoid leaving a dead process.

4. The server process is terminated
	The server sends FIN first, if the client sends data again, the server will return an RST,
	If the client reads before accepting the RST, the client receives an unexpected EOF (the server terminated prematurely).
	If the client read returns an ECONNREST after receiving the RST, "connection reset by peer", the peer resets the connection error.


5. The server process has sent FIN, and the first write causes RST. Write again, raise SIGPIPE signal

6. If the server host crashes, the client is blocked on read, and a timeout or host unreachable error is returned after a certain period of time.
  This is only discovered by actively sending errors, and there are other techniques. SO_KEEPALIVE socket option.
void sig_child(int signo)
{
	pid_t pid;
	int stat;


	while ( (pid = waitpid(-1,&stat,WNOHANG)) > 0 ) { // Loop to get the status of the terminated child process, WNOHANG does not block if there is a child process that has not been terminated
		printf("child %d terminated \n",pid);
	}
	return;
}

1 Overview






Handling the SIGCHLD signal



wait and waitpid functions



accpet terminates before returning:



Server process terminated:



SIGPIPE signal:



Server host crashes:



Restart after server host crash:









Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327045783&siteId=291194637