采用 PreForking 模型可以对子进程的数量进行了限制。PreForking 是通过预先产生多个子进程,共同对服务器套接字进行竞争性的 accept,当一个连接到来时,每个子进程都有机会拿到这个连接,但是最终只会有一个进程能 accept 成功返回拿到连接。子进程拿到连接后,进程内部可以继续使用单线程或者多线程同步的形式对连接进行处理,完整代码戳这里
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include "public_head.h"
#define LISTEN_BACKLOG 50
#define MAX_PROGRESS 1
static void grim_reaper(int sig)
{
int saved_error = errno;
while (waitpid(-1, NULL, WNOHANG) >= 0)
continue;
errno = saved_error;
}
static void handle_request(int acceptfd)
{